Display the first Image in Post as Thumbnail for WordPress Posts

What is

Let’s say you would like an easy way to display a thumbnail, no edit, no bother. The best way to do this is to detect the first image in the post and display it as a thumbnail.

First, let’s create a function that detects and returns the first image in the post:

function catch_that_image() {

  global $post, $posts;
  $first_img = '';
  $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
  if(count($matches [1]))$first_img = $matches [1] [0];
  return $first_img;

Thanks to WpRecipes for the function.

Now let’s use the Timthumb script to insert the image in the post:

<?php function my_first_image($width,$height) {

  $thumb = catch_that_image();
  if ($thumb) : ?>
    <img src="<?php echo bloginfo('template_url'); ?>/scripts/timthumb.php?src=<?php echo $thumb[0]; ?>&w=<?php echo $width; ?>&h=<?php echo $height; ?>&zc=1&q=100" alt="<?php the_title(); ?>" width="<?php echo $width; ?>" height="<?php echo $height; ?>" border="0" />
  <?php endif; ?>
Call this function wherever you want to display the thumbnail. For some reason this doesn’t work if the first image in the post is a caption, I don’t know why.


  1. My brother recommended I may like this website. He used to be entirely right.
    This submit truly made my day. You cann’t believe just how a lot time I had spent for this information! Thanks!


Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.