Are you looking for a way to display featured image caption in WordPress? While there’s probably a plugin for this, we have created a quick code snippet that you can use to display featured / post thumbnail image caption in WordPress.
Instructions:
All you have to do is add this code to your theme’s functions.php file or in a site-specific plugin:
function the_post_thumbnail_caption() { global $post; $thumbnail_id = get_post_thumbnail_id($post->ID); $thumbnail_image = get_posts(array('p' => $thumbnail_id, 'post_type' => 'attachment')); if ($thumbnail_image && isset($thumbnail_image[0])) { echo '<span>'.$thumbnail_image[0]->post_excerpt.'</span>'; } }
Add this code within the loop of the desired template file, single.php or, index.php to display featured image caption.
<? the_post_thumbnail_caption(); ?>
Note: If this is your first time adding code snippets in WordPress, then please refer to our guide on how to properly add code snippets in WordPress, so you don’t accidentally break your site.
If you liked this code snippet, please consider checking out our other articles on the site like: 12 best WordPress plugins for bloggers and how to create a multi-page form in WordPress.
thanks a lot, this works like a charm! Also works with a shortcode: just replace “echo” in the function with “return” and place a shortcode somewhere on your page.
Hmmm. This is beaking my wp 5.2.2 website, with latest avada theme :-/
Do you have a way to do this through multiple posts? We have solved the issue of showing the caption for a featured image. But, when we use that same image in a different post, all hell breaks loose.
The idea would be to add this to your loop, unless I’m not following what you mean can you provide more details?