Skip to content

Instantly share code, notes, and snippets.

@hqhow
Last active April 19, 2020 05:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hqhow/36beb6aad5d150006171732b9bd93504 to your computer and use it in GitHub Desktop.
Save hqhow/36beb6aad5d150006171732b9bd93504 to your computer and use it in GitHub Desktop.
WordPress Simple Thumbnail Function

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().'';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment