Get the first image from wordpress posts(content)

There’s a lot of ways to get the first image from wordpress posts.

I’ve found a workaround, using the function bellow. Just Put it on your “functions.php” file.

function get_first_image($content,$wdt,$hgt) {
	$first_img = '';
	$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $content, $matches);
	$pref_img = $matches [1] [0];

	if(empty($pref_img)){ //Defines a default image
		$pref_img = "";
	}
	else{
		$posgif = strrpos($pref_img , ".gif", 0);
		if($posgif > 0){
			$iext = "gif";
			$posimg = $posgif;
		}
		$posjpg = strrpos($pref_img , ".jpg", 0);
		if($posjpg > 0){
			$iext = "jpg";
			$posimg = $posjpg;
		}
		$posjpeg = strrpos($pref_img , ".jpeg", 0);
		if($posjpeg > 0){
			$iext = "jpeg";
			$posimg = $posjpeg;
		}
		$pospng = strrpos($pref_img , ".png", 0);
		if($pospng > 0){
			$iext = "png";
			$posimg = $pospng;
		}
		$first_img = substr($pref_img, 0, $posimg).".".$iext."?w=".$wdt."&h=".$hgt;
	}	
	return $first_img;
}

Call it in your code, like this:

<img src="<?php echo get_first_image_mat(get_the_content(),230,138);?>" border="0" style="width:230px;height:138px">

,

  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: