I love using the Featured Image in WordPress. I even love developing with the Featured Image and using in in various places within a theme. No matter whether its a custom post type, post format or simply the single.php, using the Featured Image is an effective method of drawing attention to a post.
In this tutorial I will walk you through an effective use of the Featured Image in WordPress.
Function you should be familiar with before reading on:
add_image_sizehas_post_thumbnailandthe_post_thumbnailedit_post_linkAlso a familiar grasp of WordPress development
In the WordPress admin area you will find the place to upload a Feature Image, but only if your theme adds the support. If it does, you will see a meta box like the one to the right. If it does not, you can read how to add the support here.
Add Feature Image to you Theme
Adding the featured image to your theme is quite simple. But before you do, let’s declare some new image sizes. This will help us by defining a specific image size to refer to later. The following function will create the image sizes. Simply add it to your functions.php file.
<?php add_image_size( 'single-thumbnail', 300, 150, true); ?>
The first parameter is the name of the image for referencing later, the second is the width, then comes the height and lastly its whether to crop the image or not.
Once we have the image size we can open the file where we want to add the image. In this case we are going to add it to the single.php. Some where after the loop is called. This is the standard method of adding the image and the following function will do the trick.
<?php
if ( has_post_thumbnail() ) {
the_post_thumbnail( 'single-thumbnail' );
}
?>
Adding the Edit Post Link
One thing I like to do with themes is remind users that the ability to add a feature image exists. Let’s face it, some users either to not know or simply forget about useful features. One way to remind users (without letting readers know) is to use the edit_post_link in an else statement. Let’s dive in with the function.
<?php
if ( has_post_thumbnail() ) {
the_post_thumbnail('single-thumbnail');
} else {
edit_post_link('Edit Post - TIP: Set Feature Image');
}
?>
Now every time the user forgets to set a feature image, this will remind her. Pretty cool huh? Well, let not stop there. After all, the edit_post_link can handle another parameter: a default image. This time, when we add the edit_post_link let’s pass a new parameter:
<?php edit_post_link(<img src=" . get_bloginfo(stylesheet_directory) . /path-to-image.jpg" width="300" height="150" />); ?>
Assuming you created a default image and placed it somewhere in your theme folder (this stuff should be obvious), every time the user forgets to add a feature image on a post, the default image will show up when she previews or views the post.