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

5

14

I'm trying to get the captions from images in Wordpress but I can't find an easy function to grab this bit of information.

Anyone know a way to get this?

Thanks

Stomatology answered 23/10, 2009 at 22:37 Comment(0)
S
4

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.

Stomatology answered 23/10, 2009 at 23:8 Comment(0)
A
18

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.

Apricot answered 18/12, 2012 at 3:9 Comment(0)
S
4

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.

Stomatology answered 23/10, 2009 at 23:8 Comment(0)
D
1

Using Wordpress 4.8, this little guy worked for me:

<?php the_post_thumbnail_caption(); ?>
Dieppe answered 21/6, 2017 at 15:22 Comment(0)
D
0

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>'; }
Dustup answered 28/10, 2015 at 13:26 Comment(0)
F
0

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>'; 
}
Friend answered 24/8, 2017 at 16:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.