Get the first image inserted into a post body in WordPress

Sometimes it’s nice to show the first image on the post archive page.

This is a very simple script that does one thing. Paste it into your theme’s functions.php file:

function get_first_inserted_image() {
  global $post, $posts;
  preg_match_all('/<img.+src=['"]([^'"]+)['"].*>/i', $post->post_content, $matches);
  $first_img = $matches [1] [0];
  // Spew it out as an image
  $first_img = '<img alt="Blog Post Image" src="' . $first_img . '">';
  return $first_img;
}

Use it like this:

echo get_first_inserted_image();

Source