Display the First Image from Each of Your Posts

Posted on March 3rd, 2011

If your posts include an image that you would like to display as a thumbnail elsewhere on your blog, here is an easy way to do it with no custom fields required. Place the following code into your theme’s functions.php file:

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];

        if(empty($first_img)){
              $first_img = "/images/default.jpg"; // default image
} 
       return $first_img;
}>

Then, to call the function and display the images as thumbnails, place the following code into the desired location within your loop:

<?php echo catch_that_image(); ?>

That’s all to do. If you would like to display a default image for posts that may not have one, specify its path in the code (on the line that says “default image).

Alternate method

The same functionality can be achieved by the following method too.

Copy the following code in the functions.php

add_theme_support('post-thumbnails');
set_post_thumbnail_size( 190,140,true );
add_image_size('sw_thumb',50,50);

Then for calling the image in the site, put the following code in the source where you want to display the image.

<?php the_post_thumbnail(); ?>

The thumbnail functionality will be available in the admin panel.