1
votes
<?php $loop = new WP_Query( array( 'post_type' => 'gallery', 
        'posts_per_page' => 100 ) 
            ); 
        while ( $loop->have_posts() ) : $loop->the_post(); ?>




    <?php if ( get_post_gallery() ) :


            /* 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
            endforeach;
        endif;

 endwhile; wp_reset_query(); ?>

The above code pulls a WordPress gallery from a custom post named "gallery." Then it stores and displays the image. Is there a way to also store the caption of the gallery into a variable?

1

1 Answers

0
votes

You can get image captions from WordPress gallery using following code.

<?php $loop = new WP_Query( array( 'post_type' => 'gallery', 
        'posts_per_page' => 100 ) 
            ); 
        while ( $loop->have_posts() ) : $loop->the_post();

        if ( $gallery = get_post_gallery( get_the_ID(), false ) ) :

            $img_ids = explode( ',', $gallery['ids'] );
            /* Loop through all the image and output them one by one */
            foreach( $gallery['src'] as $key => $src ) : ?>

                <img src="<?php echo $src; ?>" class="my-custom-class" alt="Gallery image" />
                <?php
                    $image_post = get_post( $img_ids[ $key ] ); ?>
                    <p class="wp-caption-text"><?php echo $image_post->post_excerpt; ?></p>

            <?php endforeach;
        endif;

 endwhile; wp_reset_postdata(); ?>