How to show featured image CAPTION only if it exist

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:

<?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.

3 Answers
3

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>';
  }
?>

Leave a Comment