Grab the first image from a post


/ Published in: PHP
Save to your folder(s)



Copy this code and paste it in your HTML
  1. // function
  2. function catch_that_image() {
  3. global $post, $posts;
  4. $first_img = '';
  5. ob_start();
  6. ob_end_clean();
  7. $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
  8. $first_img = $matches [1] [0];
  9.  
  10. if(empty($first_img)){ //Defines a default image
  11. $first_img = "/images/default.jpg";
  12. }
  13. return $first_img;
  14. }
  15.  
  16. //template tag
  17. <?php echo catch_that_image() ?>

URL: http://www.wprecipes.com/how-to-get-the-first-image-from-the-post-and-display-it

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.