In the last 4 years I can count on one hand how many times I have needed to use the image caption or description. What’s crazy is that three of them have been in the last two months. When trying to search for the answer I was amazed at how difficult is was to find what I needed. It turns out it’s pretty simple.
There’s no fancy “get_image_caption”. That would be too easy right?
First I had to learn that there’s no fancy “get_the_image_caption”. That would be too easy right? Anyway, an image (or attachment) is treated like a post therefore you have an excerpt and the content. The excerpt is equal to the caption and content equals the description
Before we get into the good stuff you will need to make sure you have post thumbnails enabled. In your current theme, include add_theme_support( ‘post-thumbnails’ ); in the functions.php file.
Now that your theme supports Featured Images you can add one to your post. Once it’s been added you will need to call your Post Thumbnail (Featured Image) into the loop. To do this we use “the_post_thumbnail” as shown below.
<?php the_post_thumbnail( ) ; ?>
Now that we’ve got the image showing up in our post, lets add the caption. Simply paste the code below inside the loop.
<?php the_post_thumbnail(); echo get_post(get_post_thumbnail_id())->post_excerpt; ?>
If you are wanting to display the description instead of the caption you just need to change “post_excerpt” to “post_content” as below.
<?php the_post_thumbnail(); echo get_post(get_post_thumbnail_id())->post_content; ?>
Now lets say you want to take it one step further and actually style that caption. (unless you want it to look ugly) To do this all we will do is wrap the caption in a <div> and then you can add whatever id or class you prefer. To add the div use the code structure below.
<?php the_post_thumbnail(); echo '<div class="my-class">' . get_post(get_post_thumbnail_id())->post_excerpt . '</div>'; ?>
So there you have it; a really simple way to show the image caption or description in your theme. If you have other methods that you use, suggestions or additions just let me know. I would love to know how you call them too.