Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get WP gallery Image Captions?

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.

like image 344
nixon1333 Avatar asked Dec 19 '22 11:12

nixon1333


1 Answers

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.

like image 78
danwild Avatar answered Dec 24 '22 02:12

danwild