I've created a slideshow that automatically populates with images included in a post's gallery, and I want to display each image's 'caption' field as well.
I'm currently using get_post_gallery_images
to loop through the relevant images, but that only returns an array of the image's URL's, and I need the caption data. The $counter
and $sizes
variables are some extra modifiers for handling things with Flexslider, but they're not essential to looping through the images.
function get_images($post_id) {
global $post;
if( has_shortcode( $post->post_content, 'gallery' ) ) {
$gallery = get_post_gallery_images( $post->ID ); // Returns array or URLs
$counter = -1;
$sizes = ["-300x200", "-200x300"]; // Search for medium suffixes from gallery thumbs
// Loop through each image in each gallery
foreach( $gallery as $image ) {
$counter++;
$attachment = get_post($image);
echo '<li>';
echo '<img src=" ' . str_replace($sizes, '', $image) . '"';
echo ' alt="';
echo '" data-slide="';
echo $counter;
echo '" />';
echo '</li><!--end slide-->';
echo '<p class="slide-caption">';
echo '</p>';
} // End for each
} // End if
} // End function
I've found methods using wp_prepare_attachment_for_js
but I think that requires having the images attached to the post itself. I'd like to grab images from the gallery (whether or not the images are attached to this particular post) because I want the client to be able to upload via the media library without worrying about attachments. Any ideas on how to accomplish this, or do I just need to accept that attachments are necessary?
Updated code based on answer — For anyone else trying to build a Flexslider slideshow from a gallery of thumbnails... This includes extra variables to count each image and assign it a data-slide
number (which Flexslider uses for programatic linking). The answer below returns thumbnail images or whatever size the gallery is using, so I figured out a way to parse the URL and remove the size declaration to return the full size images.
// GALLERY WITH CAPTIONS
function slider_from_gallery($post_id) {
if (
$gallery = get_post_gallery( get_the_ID(), false ) ) :
$img_ids = explode( ',', $gallery['ids'] );
$counter = -1;
/* Loop through all the image and output them one by one */
foreach(
$gallery['src'] as $key => $src ) : ?>
<li>
<?php
$image_post = get_post( $img_ids[ $key ] );
$counter++; // Increase for each image, gets passed to data-slide below
$new_src = substr($src, 0, strrpos( $src, '-')) . '.jpg'; // Get full size by finding last occurance of - and adding .jpg
?>
<img src="<?php echo $new_src; ?>" class="slide-image" alt="Gallery image" data-slide="<?php echo $counter ?>" />
<p class="flex-caption"><?php echo $image_post->post_excerpt; ?></p>
</li>
<?php endforeach;
endif;
} //End function