Is there a function to get the caption for an image in wordpress

别来无恙 提交于 2019-11-29 01:35:26

If you are trying to get the caption while in a post you can echo it out inside your "the_post_thumbnail" tag.

<?php the_post_thumbnail();
echo get_post(get_post_thumbnail_id())->post_excerpt; ?>

You can also use the same method to show the image description. This is a little better feature in WordPress 3.5

<?php the_post_thumbnail();
echo get_post(get_post_thumbnail_id())->post_content; ?>

If you need to style the caption or description you can wrap it in a div like below.

<?php the_post_thumbnail();
    echo '<div class="myDiv">' . get_post(get_post_thumbnail_id())->post_excerpt . '</div>'
; ?>

Hope that helps.

Turns out captions are stored as post excerpts. So,

<?php echo $post->post_excerpt; ?>

will print out the caption if you are on the attachment image page (image.php in your theme) and inside the Loop.

Using Wordpress 4.8, this little guy worked for me:

<?php the_post_thumbnail_caption(); ?>

I'm using this code, It works fine.

$get_description = get_post(get_post_thumbnail_id())->post_excerpt; if(!empty($get_description)){//If description is not empty show the div    echo '<div class="img-caption">' . $get_description . '</div>'; }
user3794429

Put this inside figure tag of your single.php file

$image_caption = get_post(get_post_thumbnail_id())->post_excerpt;
if(!empty($image_caption)) { 
    echo '<figcaption itemprop="caption">' . $image_caption . '</figcaption>'; 
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!