Getting Featured Image Caption to Only Show if Populated

I’m trying to hide the featured image caption from showing. Currently, it’ll show build the div (but not populate it because it’s empty). What I’d like to do, ideally, is only show the div if someone has entered text in the Caption (post_excerpt) box in the Media Panel.

This is the code I’m working off of:

Read More
    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>';
      }
    }

This is what I’ve attempted on my own to try and hide the caption if it’s empty:

    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'));
      $thumbnail_caption = $thumbnail_image[0]->post_excerpt;
      $thumbnail_set = isset($thumbnail_image[0]);

        if (! empty($thumbnail_set)) {
          if ($thumbnail_image && isset($thumbnail_image[0])) {
            echo '<div class="img-caption"><h5>'.$thumbnail_caption.'</h5></div>';
          } else return;
      } else return;
    }

This is the code in my page template:

    <section class="entry-content">
        <?php if ( has_post_thumbnail() ) : ?>
            <figure class="featured-img alignright">
                <?php the_post_thumbnail('med_size'); ?>
                <?php the_post_thumbnail_caption(); ?>
            </figure><!-- .entry-page-image -->
        <?php endif; ?>
      <?php the_content(); ?>
    </section>

When I delete the caption on the featured image. It goes away, but the div is still being created as well as the emtpy h5 element.

Here are screen captures of the two states:

link to when a caption is left blank

here is a link when a caption is filled in

Thanks for the advice and help!

Related posts

Leave a Reply

2 comments

  1. As of WordPress 4.6, the function the_post_thumbnail_caption() has been added to core (/wp-includes/post-thumbnail-template.php).

    Using the code posted here will cause the error:

    Fatal error: Cannot redeclare the_post_thumbnail_caption()