How to display featured image caption only if exists?

I’m using this function in my functions.php to display image caption for faetured images:

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 '<div class="front-caption">'.$thumbnail_image[0]->post_excerpt.'</div>';
}
} 

And using this in the template file to display the caption:

Read More
<?php 
if (the_post_thumbnail_caption()) { 
 the_post_thumbnail_caption(); 
}
?>

In the functions file I have the caption displaying in a div class=”front-caption” which I am styling with borders. If the caption does not exist then it still displays the empty bordered div.

If no caption exists I do not want to display the bordered div. I just want it to display nothing.

How can I properly code this to work? Thanks in advance.

Related posts

4 comments

  1. I am a “little late” but this solution worked great for me. It will show the div only if the caption is not empty.

    <?php
    $get_description = get_post(get_post_thumbnail_id())->post_excerpt;
    the_post_thumbnail();
      if(!empty($get_description)){//If description is not empty show the div
      echo '<div class="featured_caption">' . $get_description . '</div>';
      }
    ?>
    
  2. Please note that as of WordPress 4.6, the function has been added to core (/wp-includes/post-thumbnail-template.php).

    Using the code previously posted here will cause the error:

    Fatal error: Cannot redeclare the_post_thumbnail_caption()

    To avoid this, please name the function something else, or if catering for earlier versions of WordPress in a theme, add a check like so:

    if ( ! function_exists( 'the_post_thumbnail_caption' ) ) {
     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])) {
        return '<div class="front-caption">'.$thumbnail_image[0]->post_excerpt.'</div>';
       } else {
         return;
       }
     }
    }
    
  3. You could try this :

    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])) {
       return '<div class="front-caption">'.$thumbnail_image[0]->post_excerpt.'</div>';
      } else {
        return;
      }
    } 
    

    and then :

    echo the_post_thumbnail_caption(); 
    

Comments are closed.