Bringing High Tech to the Low Tech World.

Extract Image From WordPress Post

This will extract an image from a wordpress post. You can use it in the loop with get_content() or get_excerpt(). There are a hundred other different uses for something like this as well. Good snippet to have.

// Pull first image thumbnail from post if none exist, default to a category image.
//
// Required:
$pattern = '/<img[^>]+src[\\s=\'"]';
$pattern .= '+([^"\'>\\s]+)/is';
// Optional:
$style = "height:50px;width:60px;margin-top:15px;";
$defaultImgURL = "http://www.yoursite.com/image/url.png";
$imgAlt = "Alt Text Here";
$imgID = "";
$imgName = "";
// If we have an Image ...
if(preg_match($pattern,get_the_content(),$match)) {
	echo "<img alt=\"\" style=\"" . $style . "\" src=\"" . $match[1] . "\" />";
// If there is no img Tag ...
} else {
	echo "<img alt=\"\" style=\"" . $style . "\" src=\"". $defaultImgURL  ."\" />";
}
// Thats it!

Tags: , , ,
Posted in Blog, Hints, Technical · April 28th, 2010 · Comments (0)

Comments are closed.

Get Adobe Flash playerPlugin by wpburn.com wordpress themes

Recent Posts

Categories

Blogroll

Pages

Archives

Tags

add-ons ads advertisement advertising Adware animations ant-virus Anti-Virus apple applications art artist awesome cellular chicken cluttered computers contact dialog dinner dock downloads environment fake firefox free Freeware google hint iphone News pdf Pictures Politics power screenshot Security Spyware system tools Tricks tweet twitter Windows workspace

What I'm Doing...