KrisChase.com

How to Grab first image from wordpress post content

Posted in Web Development on 06.10.2015 by @chasebadkids

Sometimes you might find yourself in a situation where you have pages / posts that don’t have a featured image set but you want to pull an image to use on a listings page or some other page in your WordPress theme.

The following code will give you the ability to do just that.  It parses the content of the post and pulls in the first image that comes back.

 

function catch_that_image($the_post) {
  global $post, $posts;
  $first_img = '';
  ob_start();
  ob_end_clean();

  $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $the_post->post_content, $matches);
  $first_img = $matches[1][0];

  if(empty($first_img)) {
    // No image was found in body copy, let's set a default image to go with.
    $first_img = "default_image.jpg";
  }
  return $first_img;
}

 

Menu