Tech Notes: WordPress Featured Images with Captions

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);
  }
?>

Tags: , , , , ,

5 Responses to “Tech Notes: WordPress Featured Images with Captions”

  1. Marc August 21, 2012 at 2:50 am #

    I was looking for this! Hope it works. You forgot to mention where (in which file) the above code should be.

    • Ross Wintle August 21, 2012 at 10:12 am #

      Ah, you know what. I’ve just realised that the code I entered into the WordPress editor isn’t quite published properly. Let me make it right!

      Thanks for the note about where to put the code too. I’ll add something about that. More soon.

      • Ross Wintle August 21, 2012 at 11:11 am #

        There – updated the post for you – the code now displays correctly and I’ve mentioned where to add it. Thanks for pointing out my errors!

  2. Chuck March 6, 2013 at 9:05 pm #

    Thanks for this — it looks to be exactly what I was looking for. Can you tell me, though, where to add the shortcode? I put it as the first thing in the post, but that’s clearly not right.

    • Ross Wintle March 21, 2013 at 4:13 pm #

      Hi Chuck, sorry it took a while to get back to you. You need to put this code in your theme template file, at the point at which you want the image with caption to appear. It needs to be within “The Loop”.

      Hope that helps.

Leave a Reply