Posted By

crs on 09/01/09


Tagged

image wordpress thumbnail


Versions (?)

Who likes this?

2 people have marked this snippet as a favorite

tandouri
umang_nine


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


 / Published in: PHP
 

  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  

You need to login to post a comment.