Simple WordPress thumbnail function


/ Published in: PHP
Save to your folder(s)



Copy this code and paste it in your HTML
  1. function vp_get_thumb_url($text)
  2. {
  3. global $post;
  4.  
  5. $imageurl="";
  6.  
  7. // extract the thumbnail from attached imaged
  8. $allimages =&get_children('post_type=attachment&post_mime_type=image&post_parent=' . $post->ID );
  9.  
  10. foreach ($allimages as $img){
  11. $img_src = wp_get_attachment_image_src($img->ID);
  12. break;
  13. }
  14.  
  15. $imageurl=$img_src[0];
  16.  
  17.  
  18. // try to get any image
  19. if (!$imageurl)
  20. {
  21. preg_match('/<\s*img [^\>]*src\s*=\s*[\""\']?([^\""\'>]*)/i' , $text, $matches);
  22. $imageurl=$matches[1];
  23. }
  24.  
  25. // try to get youtube video thumbnail
  26. if (!$imageurl)
  27. {
  28. preg_match("/([a-zA-Z0-9\-\_]+\.|)youtube\.com\/watch(\?v\=|\/v\/)([a-zA-Z0-9\-\_]{11})([^<\s]*)/", $text, $matches2);
  29.  
  30. $youtubeurl = $matches2[0];
  31. if ($youtubeurl)
  32. $imageurl = "http://i.ytimg.com/vi/{$matches2[3]}/1.jpg";
  33. else preg_match("/([a-zA-Z0-9\-\_]+\.|)youtube\.com\/(v\/)([a-zA-Z0-9\-\_]{11})([^<\s]*)/", $text, $matches2);
  34.  
  35. $youtubeurl = $matches2[0];
  36. if ($youtubeurl)
  37. $imageurl = "http://i.ytimg.com/vi/{$matches2[3]}/1.jpg";
  38. }
  39.  
  40.  
  41. return $imageurl;
  42. }
  43.  
  44. //Use
  45. global $post;
  46. $thumb=vp_get_thumb_url($post->post_content);
  47. if ($thumb!='') echo '<img style=" width:150px;" src="'.$thumb.'" alt="'. get_the_title().'" />

URL: http://www.prelovac.com/vladimir/simple-wordpress-thumbnail-function

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.