Featured Image
It's a caption... on a featured image!

Most WordPress users are familiar with the option of adding captions to photos. However, we recently discovered that there is not a default solution for adding captions to Featured Images, a core WordPress component that is commonly used on sites – including the JacksonSky.com blog.

Through some of our own research and browsing, we compiled the following code from bits and pieces of tutorials we found online. What makes ours unique is that once it’s determined if there is a featured image, it will check again to see if there is a caption. If there is a caption, it will add a class that wraps around the featured image and the caption. It also gives the caption a container to assist with styling. (Other options we found online just added a caption outside of the image.)

To incorporate this option on your site, simply copy and paste the code below into your WordPress loop where you want the featured image to appear. (Don’t forget to first enable support for Featured Images in your functions.php file.)

<?php
if ( has_post_thumbnail() ): ?>
<?php
$caption = get_post(get_post_thumbnail_id())->post_excerpt;?>
<?php if($caption): ?>
<div class="featuredCaptionContainer">
<?php the_post_thumbnail();?>
<div class="featuredCaption"><?php echo $caption ?></div>
</div>
<?php else: ?>
<?php the_post_thumbnail();?>
<?php endif; ?>
<?php endif; ?>

Once you’ve added this, you should add these styles to your CSS file (style.css) and edit them to match your site.

.featuredCaptionContainer {
width: 100%;
border: 1px solid #e9e9e9;
padding: 1.05263157894737%;
margin-bottom: 22px;
height: auto;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
.featuredCaptionContainer img.wp-post-image {
width: 100%;
border: 0;
padding: 0;
padding-bottom: 1.05263157894737%;
margin-bottom: 0;
height: auto;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
.single-post .featuredCaptionContainer .featuredCaption {
width: 100%;
border: 0;
padding: 0;
height: auto;
color: #9B9B9B;
background: #FCFCFC;
text-align: left;
font-size: 12px;
padding: 4px 8px;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}

Once the above code has been added to your PHP and CSS files, the option to add a caption to your Featured Images will appear once you select the Featured Image, as shown in the screen capture below.

featuredcaption-dashboard

Sources & Credits:
How to Display WordPress Post Thumbnails with Captions

Share this article
Related Posts

One response to “How To Add a Caption to Featured Images”

  1. Stuart Haiz says:

    Perfect! Just what I needed. Thanks.

Leave a Reply

Your email address will not be published. Required fields are marked *