WordPress added a new major feature in version 2.9 – The Post Thumbnail. Now everyone can easily make your website looks more magazine-like and professional. I will show you how to add the feature to your theme within 5 minutes.
1. Adding codes to The Loop
First of all, if you do not know what is The Loop, please refer to this page.
Open up index.php, look for:
or, your theme may be using this instead of that above:
Add these codes just before the “the_excerpt” or “the_content” line :
'alignleft') ); ?>
Explaination:
- The first line check whether “has_post_thumbnail” function exists before running the code, so that it wouldn’t causes fatal error in older wordpress version.
- has_post_thumbnail is the function that determine whether your post has post thumbnail
- the_post_thumbnail is the function that output the post thumbnail <img> tag
.
2. Using the_post_thumbnail()
According to the wordpress codex, the function’s usage is:
It can accept 2 arguments. The first argument is the thumbnail size and the second argument is the image’s attributes.
Based on the example in part 1
I used to specify the thumbnail size in array form, like in the above example (a square thumbnail of 150 pixels).
For the second argument, I added .alignleft class to the thumbnail so that it floats left. You can add more attributes like this too:
the_post_thumbnail( array( 150, 150 ), array( 'class' => 'alignleft' , 'style' => 'border:1px solid red ; margin-right:5px ;' ) );
3. Make your theme support post thumbnail
Open functions.php, scroll to the most bottom and add this before ?> (the closing php tag) :
if ( function_exists( 'add_theme_support' ) ) {
add_theme_support( 'post-thumbnails' );
}
Visit your admin panel and edit/create a post, you will then notice a new box called “Post Thumbnail” appear at the bottom right corner. You can add thumbnail there.
4. I need rectangle thumbnail
When you upload a thumbnail, wordpress generates only square thumbnails. What if you need rectangle thumbnail in your theme?
In your functions.php, look for:
add_theme_support( 'post-thumbnails' );
After that, add this in the next line:
set_post_thumbnail_size( 300, 100, true );
The first argument is width, second is height and the third is crop_flag (if true, wordpress will crop it upon creating the thumbnail, instead of resizing)
From now on, wordpress will generate an additional rectangle thumbnail of size 300 x 100 pixels everytime you upload image.
Okay, you might ask, what about my old uploaded images? I want each of them to have a rectangle thumbnail too. Fortunately, there is a plugin called “Regenerate Thumbnails” which can do the job for you automatically.
Hope this helps 🙂
This content was originally published here.