How to use your post’s first image’s thumbnail in WordPress. This is a great tutorial because once you upload an image to your post, it’s thumbnail version will be shown wherever you choose to display the thumbnail even without actually inserting the image into your post or using a custom field.
By default, if you upload an image to your post, WordPress automatically creates a thumbnail version of that image (the default size of your thumbnail can be set in the Settings > Media menu option in your WordPress control panel. Mine is set to 150×150). If you want to display that image without using this custom get function, you can either use the get_custom_meta function or for all WordPress 2.9+ installations, you can use the get_post_thumbnail() function which is easier between the two.
But, if you want to have wordpress automatically get your post’s first image’s thumbnail, here’s what you’ll need to do:
1. Add the following function to your functions.php file that can be found in Appearance > Editor, then click “Theme Functions” link on the right:
function get_post_thumbnail() {
$files = get_children('post_parent='.get_the_ID().'&post_type=attachment&post_mime_type=image');
if($files) :
$keys = array_reverse(array_keys($files));
$j=0;
$num = $keys[$j];
$image=wp_get_attachment_image($num, 'large', false);
$imagepieces = explode('"', $image);
$imagepath = $imagepieces[1];
$thumb=wp_get_attachment_thumb_url($num);
print $thumb;
else:
print "http://www.yourdomain.com/wp-content/uploads/2010/02/default-post-thumb.jpg";
endif;
}
2. Second, insert “<?php get_post_thumbnail();?>” within an img html tag like the example below:
<?php while (have_posts()) : the_post(); ?>
<div class="clearfloat">
<img src="<?php get_post_thumbnail(); ?>" alt="<?php the_title(); ?>" class="front-list_thumbnail" />
<div class="title"><a href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?></a></div>
</div>
<?php endwhile; ?>
3. Lastly, create a default thumbnail image that will be used in step 1 in case there is no image in your post.
I named my file, “default-post-thumb.jpg”
That’s it. Let me know how this works out for you.
Leave a Reply