Simple WordPress thumbnail function


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 '<img style=" width:150px;" src="'.$thumb.'" alt="'. get_the_title().'" />';

Suggested reading:


Posted in: WordPress
TAGS:, , , , , , , , , , , , , , ,
leave a comment.

Comments:

23 Comments

  1. Alfredo
    Jan 26th, 2012

    Hi Vladimir,
    I'm publishing YouTube videos using a custom field named 'videourl'.
    Any idea of how to extract the video thumbnail image from that custom field?
    Thank you sharing your codes and for all you great work!

  2. DanielSemper
    Sep 9th, 2011

    Hi,

    I have made a small improvement to your code:

    http://www.aeromental.net/2011/09/08/wordpress-how-to-create-thumbnails-in-your-index-from-youtube-videos-and-images-hosted-outside-imgur/

    It can create thumbs for images hosted outside in another service like Imgur, and also creates a default image if nothing was found.

    Thanks for the great work :) my blog looks better thanks to this.

    • Vladimir
      Sep 9th, 2011

      You are welcome, thanks for sharing

  3. zaki
    Aug 2nd, 2011

    Hey Vladimir thanks for this useful code but really i tired to get the images showing automatically in my posts in the home page i don't know what's wrong I've put the code in Function.php and again in home.php it still the same please help with these I'm using lifetime theme

  4. Michelle McGinnis
    Jun 30th, 2011

    Thank you so much for this function Vladimir! I love it and use it all the time. I had to make an adjustment recently to get it fetching the "featured image" first - posted the update on my (very lame) blog if you ever need it: http://blog.friendlywebconsulting.com/?p=177

    Thanks again!
    Michelle

  5. Jason Paul
    May 25th, 2011

    I'm not really liking that it doesn't truly re-optimize the image to the correct size. It just changes the dimensions of the regular post image. This could be a page load nightmare. I'd say perhaps it's just not complete?

    • Vladimir
      May 27th, 2011

      That's why this one is called 'simple' Jason :)

    • Michelle McGinnis
      Jun 30th, 2011

      Jason, I think you can adjust that - just add this line in where you want to display the image:

      $thumb=vp_get_thumb_url($post->post_content, 'thumbnail');

      Change 'thumbnail' to whatever image size you'd like to display (thumbnail, medium, large or a custom size).

      Cheers, Michelle

  6. Robuster
    May 4th, 2011

    Great Job!
    Really helpful.
    Thanks a bunch for sharing!
    :)

  7. Kyle
    Apr 29th, 2011

    Hi there, great function. I have one question: when, in my post, I link to a photo from another website, the thumbnail pops up fine. However, when I use my own image, the thumbnail appears pixellated. I changed the width in the code that inserts the thumbnail on my index page (). What could be causing this?

    • ba-a
      May 9th, 2011

      Hi, had the same issue, have found the solution by any chance?

  8. Richard
    Jan 18th, 2011

    Hi Vladimir, great post,

    was having a bitta trouble with your example code, kept getting "parse error" untill i realised your example code needed a ' (apostrophe) at the end... hope this helps anyone implementing the example code

    • Vladimir
      Jan 19th, 2011

      Fixed, thanks for the notice.

  9. Nico
    Nov 30th, 2010

    Thanks Goran , had to struggle through it for a while before realising this post has not been updated with your code yet.

    Great article. Thank!

  10. DJIO
    Nov 24th, 2010

    Great Job!
    Really helpful.
    Thanks a bunch for sharing!
    :)

  11. Gene
    Nov 22nd, 2010

    How do I insert the above example usage code in the homepage loop? (I don't know php ;) )

    • Vladimir
      Nov 30th, 2010

      Yes, you can supply a parameter to wp_get_attachment_image_src google the function

  12. nicole
    Nov 9th, 2010

    thank you very much! I think this is even better the the_post_thumbnail() function :)

  13. Lawrence
    Nov 1st, 2010

    is there a way to pull the medium sized image as opposed to the thumbnail? sorry, i'm not much of a programmer. thanks!

  14. Lawrence
    Oct 31st, 2010

    Thanks man! i was looking for somethign like this forever...

  15. Goran Aničić
    Oct 28th, 2010

    If video embedded in post, "preg_match" line should be changed to fetch ID:

    preg_match("/([a-zA-Z0-9\-\_]+\.|)youtube\.com\/(v\/)([a-zA-Z0-9\-\_]{11})([^<\s]*)/", $text, $matches2);

    • Vladimir
      Nov 30th, 2010

      Thanks for the tip!

  16. Jawad
    Oct 28th, 2010

    Thanks, this would remove my nightmare to manually assign thumbnail images :)

Have your say

Your email is never published nor shared. Required fields are marked *

*
*

Subscribe without commenting

About

vladimir prelovac Vladimir Prelovac is CEO of Prelovac Media, a computer engineer by profession and an adventurer by state of mind. more +


"I would love to change the world, I just don't have the source code yet."

Services

Manage multiple WordPress sites

Built for WordPress enthusiasts, ManageWP helps you manage all your WordPress sites from one central location.

Books

WordPress Plugin Devleopment Book Read my book WordPress Plugin Development: Beginner's Guide

Published by Packt Publishing, available online through Amazon.