Bringing High Tech to the Low Tech World.
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: code, hint, php, wordpress
Posted in Blog, Hints, Technical · April 28th, 2010 · Comments (0)