Posted By

LuckyShot on 12/01/09


Tagged

image wordpress


Versions (?)

Who likes this?

4 people have marked this snippet as a favorite

vintagekrug
rickfu
Blacksnipe
jlan


Wordpress - Get first image of post (without Custom Fields)


 / Published in: PHP
 

URL: http://wordpress.org/support/topic/246893

To call it just put <?php> in your template file within the loop.

  1. // Get URL of first image in a post
  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. // no image found display default image instead
  11. if(empty($first_img)){
  12. $first_img = "/images/default.jpg";
  13. }
  14. return $first_img;
  15. }
  16.  
  17. // With TimThumb
  18. <img src="/thumb.php?src=<?php echo catch_that_image() ?>&w=200&zc=1&q=200" alt="<?php the_title(); ?>"/>

Report this snippet  

You need to login to post a comment.