How to get a thumbnail of a WordPress post by ID

November 16th, 2009 by Alex Leave a reply »

When you need to get a post thumbnail in WordPress, and to use it your own way, use the next function which will come handy. First, it searches for attached images, then if if doesn’t find any and you pass the post content, it seeks the content for all tags.

function get_thumb($postid, $content='') {
  $images =& get_children('post_type=attachment&post_mime_type=image&post_parent='.$postid);
  $thumbs = null;
  if ($images) {
    foreach($images as $k=>$v) {
      $thumbs[] = wp_get_attachment_image_src($k, 'thumbnail', false);
      break;
    }
  }
  if (!$thumbs && $content) {
    preg_match_all('%<img(.*?)src="(.*?)"(.*?)>%i', $content, $img);
    for($a = 0; $a < count($img[0]); $a++) {
      $thumbs[] = array($img[2][$a], '<img src="'.$img[2][$a].'" />');
    }
  }
  return $thumbs;
}

It returns an array of found images, with the url on first place, and a ready tag at the second. Place this function in your functions.php to use it anywhere you want. Some sample function call can look like this in you WordPress Loop:

...
the_post();
$thumbs = get_thumb($post->ID, $post->post_content);
if ($thumbs) {
echo $thumbs[0][1]; // echo the first image tag
echo $thumbs[0][0]; // echo the first image url
}
...

Comments are closed.