I’m trying to grab gallery images and it’s info of a post through a loop. All i’m getting image sources but not the captions. Here is my code
<?php
/* The loop */
while ( have_posts() ) :
the_post();
if ( get_post_gallery() ) :
$gallery = get_post_gallery( get_the_ID(), false );
/* Loop through all the image and output them one by one */
foreach( $gallery['src'] AS $src ) {
?>
<img src="<?php echo $src; ?>" class="my-custom-class" alt="Gallery image" />
<?php
}
endif;
endwhile;
?>
Using this loop i’m only getting source of the images of the gallery in a post. But I want to grab the image captions too.
Found a solution on wordpress.org:
Stick this in your functions.php:
Then you can just pass in the id and grab whatever meta you need like this:
And then either loop through the array values or simply reference by the key name of what you want (ie: caption, description, etc.):
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:
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
You can try to print the value of these functions and use it as per your requirement