This tip created by HQHow.com
Here is a quick function to extract the thumbnail image from the post. This is quite useful especially on older themes or if you are not using post thumbnail functionality of newer WordPress versions.
The function can be called within the loop. It will scan for image attachments and return the URL to thumbnail of the first image.
If no attachments are found, it would return the URL of the first image found (for example an externally linked image).
If no images are found, but a youtube video is embedded, it would return the thumbnail of the youtube video.
function vp_get_thumb_url($text)
{
global $post;
$imageurl="";
// extract the thumbnail from attached imaged
$allimages =&get;_children('post_type=attachment&post;_mime_type=image&post;_parent=' . $post->ID );
foreach ($allimages as $img){
$img_src = wp_get_attachment_image_src($img->ID);
break;
}
$imageurl=$img_src[0];
// try to get any image
if (!$imageurl)
{
preg_match('/<\s*img [^\>]*src\s*=\s*[\""\']?([^\""\'>]*)/i' , $text, $matches);
$imageurl=$matches[1];
}
// try to get youtube video thumbnail
if (!$imageurl)
{
preg_match("/([a-zA-Z0-9\-\_]+\.|)youtube\.com\/watch(\?v\=|\/v\/)([a-zA-Z0-9\-\_]{11})([^<\s]*)/", $text, $matches2);
$youtubeurl = $matches2[0];
if ($youtubeurl)
$imageurl = "http://i.ytimg.com/vi/{$matches2[3]}/1.jpg";
else preg_match("/([a-zA-Z0-9\-\_]+\.|)youtube\.com\/(v\/)([a-zA-Z0-9\-\_]{11})([^<\s]*)/", $text, $matches2);
$youtubeurl = $matches2[0];
if ($youtubeurl)
$imageurl = "http://i.ytimg.com/vi/{$matches2[3]}/1.jpg";
}
return $imageurl;
}
Here is example usage within the home page loop to show the post thumbnail in the excerpt (this is actually used on my homepage).
global $post;
$thumb=vp_get_thumb_url($post->post_content);
if ($thumb!='') echo ''. get_the_title().'';