Advertisement
salmancreation

How to: Get the first image from the post and display it

Jan 14th, 2015
204
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 0.56 KB | None | 0 0
  1.  
  2. First, paste this function on your functions.php file.
  3.  
  4. function catch_that_image() {
  5.   global $post, $posts;
  6.   $first_img = '';
  7.   ob_start();
  8.   ob_end_clean();
  9.   $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
  10.   $first_img = $matches [1] [0];
  11.  
  12.   if(empty($first_img)){ //Defines a default image
  13.     $first_img = "/images/default.jpg";
  14.   }
  15.   return $first_img;
  16. }
  17.  
  18.  
  19.  
  20. Once done, you can simply call the function within the loop to display the first image from the post:
  21. <?php echo catch_that_image() ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement