Featured Image with Caption

More WordPress jiggery pokery today. The challenge this time: I want to use a featured image, but with a caption!

No one seems to have a definitive solution to this, though several partial solutions exist. The trick is to get the image formatted using the standard caption styles, so they look like any other captioned image on your site.

I’ve pulled together info from a couple of sources to concoct my own recipe for doing it “properly”.

Sources

Solution

Here’s the code. It’s pretty self-explanatory.  You just need to put this in your template file where you want the image to appear.

The only thing to look out for is that the shortcode demands both a caption and a width parameter to be passed, otherwise it generates nothing. Oh, and I remove the title – tooltips look messy!

<?php
  if (has_post_thumbnail()) {
    $thumbnail_id = get_post_thumbnail_id( get_the_ID());
    $thumbnail_caption = get_post_field('post_excerpt', $thumbnail_id );
    $thumbnail_image = get_the_post_thumbnail(get_the_ID(), 'my_image_size', array( 'title' => '' ));
    $caption_shortcode = sprintf('[caption width="440" caption="%s"]%s[/caption]', $thumbnail_caption, $thumbnail_image);
    echo do_shortcode($caption_shortcode);
  }
?>