How to get first image of post WordPress?

This article was written by in March 18, 2015, & may not be posted on other sites!
Original source url for this article: How to get first image of post WordPress?

How to get first image of post WordPress?
If you are NOT using featured image and just want to get the first image of the post content, this is the solution. This is how to get first image of post in WordPress.

How to get first image of post WordPress?

How to get first image of post WordPress?

    1. Start by opening the functions.php and add the following code:
      <?php
      /*get first image of post--------*/
      function catch_first_image(){
      global $post, $posts;
      $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)){ //If no image is found
      $first_img = "/images/default.png"; //path to default image
      }
      return $first_img;
      }
      ?>
    2. Make sure to replace the url of the default image to match your default image url. The default image will be used if there is no image in the current post

 

To get the first image of a post from inside the loop, use this code:

<?php echo('<img src="' . catch_first_image() . '" />'); ?>

 

To get the first image of a post from outside the loop, use this code:

<?php
$id = 12; //ID of the page or post
$post = get_post($id);
echo('<img src="' . catch_first_image() . '" />');
?>

 

Spread the word

Facebooktwittergoogle_pluslinkedinmail

Leave a Reply

Your email address will not be published. Required fields are marked *