Wordpress Display First Post Image


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



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

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.