Retreive First Image From Post
-
I have been looking around for this for ages. I have been using other post thumb plugins and just find them to bulky for what i wanted, too feature rich. I just wanted a basic grab the first image from a post and display it. Just add the below code to your functions.php file in your theme directory.
// Get URL of first image in a 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); $first_img = $matches [1] [0]; // no image found display default image instead if(empty($first_img)){ $first_img = "/images/default.jpg"; } return $first_img; }
to call it just put <?php echo catch_that_image() ?> in your template file within the loop.
I am using this in conjunction with https://code.google.com/p/timthumb to scale the image to what i want it to be. and i would just do
<img src=”/thumb.php?src=<?php echo catch_that_image() ?>&w=200&zc=1&q=200″ alt=”<?php the_title(); ?>”/>
- The topic ‘Retreive First Image From Post’ is closed to new replies.