With most themes WordPress makes it really easy to add a featured image to an article / a post or a page. But although the image caption is often added correctly to inline images, it is often missing from featured images. So how can you add a Caption to the Featured Image in WordPress easily? And why do you need a caption after all?
Missing captions don’t have to be a problem for most use cases. But if you are using you WordPress installation as a CMS for some type of a magazine style website, you might want to – or even have to add captions to all images shown on your website – for example to give credit to the source of the image, the agency, the photographer – and to mention the license of the image. Some licenses require that you mention the license and the name of the photographer together with a link to the origin of the image. Then you’ll even have to add a bit of HTML to the caption. And as so often with WordPress the good news is that this is very well achievable with only a few lines of code added to your template files.
How to add a Caption to the Featured Image
First of all, remember to make the following adjustment inside your child theme. If you don’t use a child theme yet, now is the time. If you don’t know how to add a child theme to your WordPress installation you may first want to read this previous article: How to create a Child Theme for WordPress in Minutes.
In your template file (content.php or single.php or content-single.php or page.php etc) you would then need to find the section where the featured image is actually called. The respective code should be look similar to the following code:
<div class="entry-thumbnail">
<?php the_post_thumbnail(''); ?> <!-- the featured image -->
</div>
Depending on the theme and/or template you might also find something like this:
<?php if ( ! post_password_required() && ! is_attachment() ) : the_post_thumbnail('large'); endif; ?>
Below the above code you would simply have to add the following:
<?php if ( $caption = get_post( get_post_thumbnail_id() )->post_excerpt ) : ?> <p class="caption"><?php echo $caption; ?></p> <?php endif; ?>
What the above code does is first check if you have a post thumbnail a.k.a. featured image at all – then also check if the image has a caption (“post_excerpt”). If both are TRUE a paragraph with the class “caption” is printed to the layout, echoing the actual caption.
You can then add appropriate styling to the caption to make it fit your theme design.
Excellent tutorial! Really your tutorial is fully informative. This codes very simple and easy to used. It’s quite flexible and easy to used.
Thanks.