How to get first image from content post wordpress

These the simplest way how to get first image from content post wordpress and display it.

First, paste this function code on your functions.php file :

function get_first_image() {
 global $post, $posts;
 ob_start();
 ob_end_clean();
 $my_img = '';
 $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
 $my_img = $matches[1][0];

 if(empty($my_img)){
  $my_img = "<img src='default.jpg'>";
 }else{
  $my_img = "<img src='".$my_img."'>";
 }
 return $my_img;
}

After that, call the function within the loop to display the first image from the post :

<?php echo get_first_image() ?>