Display the First Image in Post as Thumbnail for WordPress Posts

1
Display the First Image in Post as Thumbnail for WordPress Posts - techinfoBiT

We have already published an article about WordPress thumbnail image with the title “How To Add Thumbnails to WordPress Posts | Enable Featured Image“. In this post, I am going explain a hook that will make the setting thumbnail image even easier.

So, let’s create a function that detects and returns the first image in the 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);   if(count($matches [1]))$first_img = $matches [1] [0];   return $first_img; }

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. I have tried this codes but for me, it did not work when I was adding the caption to the images so you may consider avoiding the caption for the images.

Via: WPRecipes

LEAVE A REPLY

Please enter your comment!
Please enter your name here

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