WordPress Wednesdays: Display a thumbnail image with post excerpts

Geek Factor: 3

The website WP Recipes offers up this helpful code snippet to help get the first image from a post, and to display that image as a thumbnail with the post excerpt.

In WP Recipe’s example, a default image was set to be used when the post didn’t have an image. When I first tried out this code, not many of the posts I was working with actually had images; rather than display a string of filler images on those posts, I tweaked the code so no image was loaded instead.

Depending on your needs — whether or not posts on your site frequently have images or not — you can copy the below code, or get the original from WP Recipes.

Add this function to the functions.php file:

[php]
function catch_that_image() {
global $post, $posts;
$first_img = ”;
ob_start();
ob_end_clean();
$output = preg_match_all(‘//i’, $post->post_content, $matches);
$first_img = $matches [1] [0];

if(empty($first_img)){ //Can be used to define default image path
$first_img = “”;
}
return $first_img;
}
[/php]

And then use this snippet in the loop to display the image:
[php]

[/php]

If you want to wrap the image in a div, you can include that in an if statement, so it’s only outputted if the post actually has an image to use as a thumbnail:

[php]

Legal FAQ Collections