Posted By

maryann on 02/05/10


Tagged

wordpress loop


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

redstorm


Grab the first image from a post


 / Published in: PHP
 

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

  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() ?>

Report this snippet  

You need to login to post a comment.