• Home  / 
  • WordPress
  •  /  WordPress Tip #3 – Captions on Post Thumbnails

WordPress Tip #3 – Captions on Post Thumbnails

WordPress Tips

The introduction of post thumbnails (or Featured Images, as they are somewhat confusingly named in the post editor) in WordPress 2.9 made it easy to add a featured image to your posts, without the use of custom fields.

This image can be used as a thumbnail image in your list of posts on an archive page or your blog page, and can also be used in your post template, to add the featured image to the top of each post, as you can see on this site.

However, when you add an image as a post thumbnail, even if you add a caption, the caption will not be displayed by default.

We often use Creative Commons images as our post thumbnails, and we like to credit the image owner in the caption, so we needed a way of displaying the image caption underneath the featured image.

To do so, you just need the following code:

<?php if(has_post_thumbnail()) { ?>

	<div class="post-featured-image">

		<?php the_post_thumbnail();
			if(get_post(get_post_thumbnail_id())->post_excerpt) {
				echo '<div class="post-thumbnail-caption">' . get_post(get_post_thumbnail_id())->post_excerpt . '</div>'; } ?>
	</div>

<?php } ?>

The way this works is that every image is saved as an attachment, which is a kind of post, and the image caption is saved as the excerpt of that post.

So this code checks whether this image has a caption, and if so, it is displayed below the featured image.

About the author

Dan Johnson

Dan used to be a WordPress developer at WDFS, but now he has gone off to pursue his passion for art, and he blogs about making a living from creativity at Right Brain Rockstar

Comments are closed