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


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

To call it just put


Copy this code and paste it in your HTML
  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(); ?>"/>

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

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.