phprockers-logo

How to get URL of first image in a post

We can easily grab the first image from the post, and display it. 


// Get URL of first image in a post
function get_first_image() {
         global $post;
         $first_img = ''; 
         ob_start();
         ob_end_clean();
         $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
         $first_img = $matches [1] [0];
         if(empty($first_img)){
                  $first_image = "/images/default.jpg";
        }
        return $first_image;
}


<?php echo catch_that_image() ?>

1 comment:

  1. I have used this.... It is so helpful for me

    ReplyDelete