How to get WP gallery Image Captions? How to get WP gallery Image Captions? wordpress wordpress

How to get WP gallery Image Captions?


Found a solution on wordpress.org:

Stick this in your functions.php:

function wp_get_attachment( $attachment_id ) {    $attachment = get_post( $attachment_id );    return array(        'alt' => get_post_meta( $attachment->ID, '_wp_attachment_image_alt', true ),        'caption' => $attachment->post_excerpt,        'description' => $attachment->post_content,        'href' => get_permalink( $attachment->ID ),        'src' => $attachment->guid,        'title' => $attachment->post_title    );}

Then you can just pass in the id and grab whatever meta you need like this:

attachment_meta = wp_get_attachment(your_attachment_id);

And then either loop through the array values or simply reference by the key name of what you want (ie: caption, description, etc.):

echo $attachment_meta['caption'];

The above would echo the image's caption.

Credit goes to Luke Mlsna and sporkme for this.


The wp_prepare_attachment_for_js function is really nice for this sort of thing. It returns a TON of info about attachments, everything we'll ever need I think.

Here's the original code snipped replaced with one that makes the caption available. In this case I've placed the caption in the alt tag:

<?php/* The loop */while ( have_posts() ) :    the_post();    if ( get_post_gallery() ) :        $gallery = get_post_gallery( get_the_ID(), false );        /* create an array of IDs from  */        $gids = explode( ",", $gallery['ids'] );        /* Loop through all the image and output them one by one */        foreach ($gids as $id) {            /* pull all the available attachment data with the new function */            $attachment = wp_prepare_attachment_for_js($id);            /* Uncomment the next line to see all the available data in $attachment */            //var_dump($attachment);             /* pick and choose which bits are needed */            ?>            <img src="<?php echo $attachment['sizes']['thumbnail']['url']; ?>" class="my-custom-class" alt="<?php echo $attachment['caption']; ?>" />            <?php        }    endif;endwhile;?>

It's worth noting that this function returns all the available image sizes too, so it might be great when using a combo of custom image sizes and srcset for responsive image solutions :)


instead passing get_the_ID just pass the whole $post and use code something like this

$gallery = get_post_gallery( $post, false );$gids = explode( ",", $gallery['ids'] );foreach( $gids as $id ) {   // here you can use the $id to fetch any details of image like below and many more     wp_get_attachment_url( $id );   wp_get_attachment_metadata( $id );} 

You can try to print the value of these functions and use it as per your requirement