Here’s a quick way to pull the first image from a post using WordPress. In your functions.php file, put the following:
function getfirstimage() {
global $post, $posts;
$iimage = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
$iimage = $matches[1][0];
if(empty($iimage)){ //set a default image if post has no image
$iimage = "/images/default.jpg";
}
return $iimage;
}
If you call getfirstimage(); from within your loop, it should give you back the first image (if there is one).
The gibberish you see inside of the preg_match_all function is known as Regular Expressions. It is quite widely regarded as a mini coding language all its own. I found a limitation in the example shown above, which I use in my “On the Go” latest post in my sidebar. It seems, if there are multiple tags beside each other (like multiple pictures) with no spaces or other any other characters in between, the regular expression will keep searching until it finds the very last closing tag before a breaking character or the end of the post. Any suggestions for a fix?
