How To Use Thumbnails Generated By WordPress In Your Theme

Many WordPress Themes display post excerpts on blog homepage with a little thumbnail image of one of the images used within a post, but most of the WordPress themes I have seen, use some kind of external image resizing script like phpThumb or tinyThumb or they use some custom field in the post to show thumbnail image.

But WordPress has inbuilt functionality of generating thumbnails of the images you add to your post. This functionality is enabled by default unless you have explicitly set it from Media Settings in WordPress Settings panel.

 

Today, I’m going to show you how to use thumbnails generated by WordPress in your theme without requiring any third party script, plugin or custom field.

1. First of all set the thumbnail size to what you want in the Media Settings of WordPress.

2. Now open up index.php of your WordPress theme and inside the WordPress loop, add the following lines of code to get the path of thumbnail image of the first image in the post.

<?php
//Get images attached to the post
$args = array(
	'post_type' => 'attachment',
	'post_mime_type' => 'image',
	'numberposts' => -1,
        'order' => 'ASC',
	'post_status' => null,
	'post_parent' => $post->ID
); 
$attachments = get_posts($args);
if ($attachments) {
	foreach ($attachments as $attachment) {
		$img = wp_get_attachment_thumb_url( $attachment->ID );
                break;
        }
//Display image
}
?>

Code Explanation: Firstly we fetch the images attached to the post in the order they were added to the post. And if images are there we fetch the path to the thumbnail image of the first image in the post using wp_get_attachment_thumb_url function.

Now you have path of the image in $img which you can use to display the post thumbnail using img tag.

If you have visited the homepage of Web Developer Plus, I am using this technique to display post thumbnails with post excerpts.