You can try this function, in your functions.php file.
// automatically retrieve the first image from posts
function get_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 ) ) {
// defines a fallback imaage
$first_img = get_template_directory_uri() . "/images/default.jpg";
}
$first_img = '<img src="' . $first_img . '" alt="Post Image" />';
return $first_img;
}
This function search for first image tag in content and returns it. Then in your theme you can call image like this.
<?php
if ( get_the_post_thumbnail( $post_id ) != '' ) {
the_post_thumbnail();
} else {
echo get_first_image();
}
?>