Display Code for WordPress Featured Images

Display Code for WordPress Featured Images

The WordPress Featured Image is a great tool where ones pages and posts can be easily illustrated with a pre-configured display of any selected image that has been uploaded to the WordPress Media Library. As a WordPress theme developer, I often have to find new ways to display the featured image, or in the case of editing somebody else s WordPress theme, I may find myself using the feature image function in combination with other display tools, such as timthumb.php or ???

My preferred method is to grab the url of the featured image, then use that to construct what will be needed given the design brief. The following is my code to grab the featured image URL:

Display URL Example

<?php if (has_post_thumbnail( $post->ID )) : ?>
<?php $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'single-post-thumbnail' ); ?>
<img src="<?php echo $image; ?>" />
<?php endif; ?>

Easy peasy. How about getting it to display as an image? Note I’ve added an image class to help me style how the image will be displaying.

Image Display Example

<?php if (has_post_thumbnail( $post->ID )) : ?>
<?php $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'single-post-thumbnail' ); ?>
<img class="myFeatured-image" src="<?php echo $image; ?>" />" alt="Featured Image" />
<?php endif; ?>

Let us link that displayed image to something. In this example I’m showing the featured image in a lightbox effect:

Hyperlinked Example

<?php if (has_post_thumbnail( $post->ID )) : ?>
<?php $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'single-post-thumbnail' ); ?>
<a href="<?php echo $image; ?>" title="Featured Image" rel="fancybox"><img class="myFeatured-image" src="<?php echo $image; ?>" />" alt="Featured Image" /></a>
<?php endif; ?>

Showing the featured image full size then linking the same image to appear in a lightbox effect is silly at best. What generally occurs is displaying an image thumbnail, then having that link to the full size image. To achieve this I use the popular (and now secure) timthumb.php script found at Googleoff site icon

TimThumb.php Example

<?php if (has_post_thumbnail( $post->ID )) : ?>
<?php $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'single-post-thumbnail' ); ?>
<a href="<?php echo $image; ?>" title="Featured Image" rel="fancybox">
	<img class="myFeatured-image" src="http://your.path.to.timthumb.php?src=<?php echo $image; ?>&q=100" />" alt="Featured Image" />
</a>
<?php endif; ?>

Notes

In the above example, I’ve added q=100 which sets the rendered jpg quality to 100%. There are more variables that can be added, including how and where to crop. You will need the GD library installed on your server (who doesn’t these days). Learn more about the timthumb script and its primary developer Ben Gilbanks from Ben’s TimThumb website off site icon