CodeHQ

Grab first image from post

Function for grabbing image from post and using it instead of a featured image for example.

Add this to functions.php

// Get URL of first image in a post
function catch_that_image() {
	global $post, $posts;
		$first_img = '';
		ob_start();
		ob_end_clean();
		$matches[1][0] = '';
		if(preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches)){
		  	$first_img = $matches[1][0];
		}

	// no image found display default image instead
	return $first_img;
}

And call in the theme with

<img src="<?php echo catch_that_image() ?>" onerror="this.style.display = 'none';"/>