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.
I am a “little late” but this solution worked great for me. It will show the div only if the caption is not empty.
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:
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:
You could try this :
and then :
Most of these answers appear rather outdated. Please try this function:
Ref: https://developer.wordpress.org/reference/functions/the_post_thumbnail_caption/
For example: