Check if the post has at least one image and display it


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



Copy this code and paste it in your HTML
  1. <?php
  2. // ADD THIS IN THE functions.php FILE
  3.  
  4. function catch_that_image() {
  5. global $post, $posts;
  6. $first_img = '';
  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 = "/uploads/default.jpg";
  12. }
  13. return $first_img;
  14. }?>
  15.  
  16. ---------------------------------------------------------------------
  17.  
  18. <?php
  19.  
  20. // ADD THIS IN THE DESIRED TEMPLATE FILE
  21.  
  22. $content = $post->post_content;
  23. $searchimages = '~<img [^>]* />~';
  24.  
  25. /*Run preg_match_all to grab all the images and save the results in $pics*/
  26.  
  27. preg_match_all( $searchimages, $content, $pics );
  28.  
  29. // Check to see if we have at least 1 image
  30. $iNumberOfPics = count($pics[0]);
  31.  
  32. if ( $iNumberOfPics > 0 ) { ?>
  33. <!-- GRAB THE IMAGE AND USE WHATEVER HTML YOU LIKE -->
  34. <img src="<?php echo catch_that_image() ?>" alt="<?php the_title(); ?>" /></a>
  35. <?php }
  36.  
  37. ?>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.