Posted By

math89 on 12/22/09


Tagged

image wordpress


Versions (?)

Who likes this?

4 people have marked this snippet as a favorite

rickfu
jlan
maxvee8
Nix


Wordpress ; Get the first image from the post and display it


 / Published in: PHP
 

It allows you to automatically get the first image from the current post, and display it.

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

Report this snippet  

You need to login to post a comment.