Home > Internet marketing and seo blog > Wordpress > Print the first picture from a wordpress post

Print the first picture from a wordpress post

Catch the first image from a wordpress post? Why is there needed a function for that? There are already the “featured image” function in WordPress. Well, for many purposes, that cannot be used. For example if you have a blog where a lot of people are writing, and you are listing excerpts with a image in your front page or category pages, like I do on this blog. If you do, the easiest way is to let people use featured image in blog posts, and then you just print that one in your index.php and category.php. But the problem is, people does not always remember to use featured image. And you do not want to teach them all the time how to do. And you do not want your site’s design to break because bloggers are forgetting to use the function. Then a fallback function picking the first picture from the post is great!

The code for printing the first image from a post in WordPress:

This goes in to functions.php:

// Get URL of first image in a post
function catch_that_image() {
global $post, $posts;
$first_img = ”;
ob_start();
ob_end_clean();
$output = preg_match_all(‘/<img.+src=[\'”]([^\'”]+)[\'”].*>/i’, $post->post_content, $matches);
$first_img = $matches [1] [0];

// no image found display default image instead
if(empty($first_img)){
$first_img = “/images/default.jpg”;
}
return $first_img;
}

This goes into category.php, index.php or where ever you want to use it:

<a href=”<?php the_permalink(); ?>” title=”<?php the_title(); ?>”><img src=”<?php echo catch_that_image(); ?>” alt=”<?php the_title(); ?>” /></a>

I hope I could help you. At least the code for printing the first image from a post in WordPress helped me in at least three projects.