0

I'd like to display captions with my featured images. This is another feature that should be available by default but for some reason is not.

There are a few routines out there that claim to accomplish the task, but they come up blank for me.

Is there any reliable way to display a caption with a featured image?

1 Answer 1

2

To use this you will need to add this to in place of your themes thumbnail function:

function your_thumbnail_caption($html, $post_id, $post_thumbnail_id, $size, $attr)
{
$attachment =& get_post($post_thumbnail_id);

if ($attachment->post_excerpt || $attachment->post_content) {
$html .= '<p class="thumbcaption">';
if ($attachment->post_excerpt) {
$html .= '<span class="captitle">'.$attachment->post_excerpt.'</span> ';
}
$html .= $attachment->post_content.'</p>';
}

return $html;
}

add_action('post_thumbnail_html', 'your_thumbnail_caption', null, 5);

Your current call to the post thumbnail should work, but just in case here is the code I use in the index.php or the post.php (whichever your theme is using).

<?php the_post_thumbnail(); ?>

Now when you add a post thumbnail you can type your caption for the image. Make sure you save the image after adding the thumbnail. You can also add captions to existing thumbnails by going to the post edit screen, select the post and click the current featured image to bring up the image caption area.

3
  • Thanks, Jeremy. Well-explained, and works very well. Just one thing -- the caption behaves independently of the image. Thus, a long caption doesn't automatically break to accommodate a narrower image. Any way to adjust for that?
    – user5486
    Commented Jun 10, 2011 at 0:29
  • You can style the caption using the class .thumbcaption since it has the <p class="thumbcaption"> add inside the code. Here is an example: .thumbcaption { font-size:90%; display:block; padding:15px; background:ghostwhite; border:1px solid #ccc; width:100%; } Commented Jun 12, 2011 at 3:07
  • Sure, I realize that. But the caption does not break to accommodate an image that is narrower than the caption. A longer caption extends the width of the image+caption block. Could be that there's no way to fix this. Again, it would be nice if WordPress supported captions for thumbnails exactly the same way it supports captions elsewhere.
    – user5486
    Commented Jun 12, 2011 at 20:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.