Catch that Image

Function that will look for the featured image first, then if no featured image it will look for the first image in the post, then if no image in the post it will show the default.png in your theme’s images folder. (you have to put the default.png in your theme of course.)

Functions File:

/*-------------------------------------
	Fallback for no featured image. 
	Will grab first image in post.
---------------------------------------*/
function catch_that_image() {
global $post, $posts;
$first_img = '';
ob_start();
ob_end_clean();
if(preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches)){
$first_img = $matches [1] [0];
return $first_img;
}
else {
$first_img = get_template_directory_uri()."/images/default.png";
return $first_img;
}
}

 

Theme File:

<?php if ( has_post_thumbnail()  ) {
		  the_post_thumbnail('large');
		} else {
		   echo '<img src="';
			 echo catch_that_image();
			 echo '" alt="" />';
		}   ?>