How to display the_post_thumbnail if a post has one or otherwise display the first image in a post?

I would like to create a condition that checks to see if a post has a thumbail and if it does display it, otherwise display the first image in a post.

I tried something like this in my loop.php but it didn’t seem to work:

<?php if (has_post_thumbnail()) { ?>
<a href="https://wordpress.stackexchange.com/questions/57141/<?php the_permalink(); ?>"><?php the_post_thumbnail(array(640,320)); ?></a>
<?php } else { ?>
<a href="https://wordpress.stackexchange.com/questions/57141/<?php the_permalink(); ?>"><img src="<?php echo catch_that_image(); ?>" /></a>
<?php } ?>

This goes in my functions.php file:

<?php
    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 = get_bloginfo('template_url')."/images/no_image.gif";
        }
            return $first_img;
    }

    $imgURL = catch_that_image();
?>

2 Answers
2

Get the Image does what you need and better. It’s NOT overwhelming with lots of unnecessary features, and does what it says. Try it to see if it does what you need.

How does Get the Image plugin pull images?

  • Looks for an image by custom field (one of your choosing).

  • If no image is added by custom field, check for an image using the_post_thumbnail() (WP 2.9’s new image feature).

  • If no image is found, it grabs an image attached to your post.

  • If no image is attached, it can extract an image from your post content (off by default).

  • If no image is found at this point, it will default to an image you set (not set by default).

Leave a Comment