WordPress Tip #3 – Captions on Post Thumbnails

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.

4 Comments Leave a comment

  1. Foxtrot1 says:

    Where do you paste this code? I’ve seen different solutions around the web, and none of them say where to copy this.

  2. Ifmeister says:

    Hi. This is absolutely brilliant. I was looking for a way to credit image authors but didn’t know how to setup the conditional that would allow me to display image captions but only if they were not empty. This helped me to do just that.

    Thanks heaps!

  3. Juan Diego says:

    Hi, this is a perfect solution for editors, thanks for share it.

    This solved partially my needs:

    I just add this If to my single.php

    if(get_post(get_post_thumbnail_id())->post_excerpt) {
    echo ” . get_post(get_post_thumbnail_id())->post_excerpt . ”;

    Also I´ve created styles for the image.

    and works perfectly, except when the post has not a featured image, the post show an empty espace in the place where the featured image will be.

    This is my entire code:

    ___________________________________________

    post_excerpt) {
    echo ” . get_post(get_post_thumbnail_id())->post_excerpt . ”; }
    ?>

    _____________________________________________

    I know there is no reason to help, your post is more than perfect, let me abuse of your generosity asking for a favor:

    Can you gimme a tip to solve this problem?

    Thans a lot!

    -jd

  4. Juan Diego says:

    Sorry the comments just cut the code:
    http://prntscr.com/1ecwpw