Getting the image title/alt attribute from the gallery shortcode

A little background: WP stores the attachments in the same database table as posts. Therefore the table rows correspond to the fields of the media edit modal:

http://i.imgur.com/1i2gfLE.jpg

get_post_gallery_images will return you URLs to the images, but not the actual data in the database. You could do a reverse-query and look for posts that contain the image URL but that would be more difficult than necessary.

Instead use the get_post_gallery function. This one is actually used by get_post_gallery_images too, but also returns the IDs of the attachments in an array. Use these IDs to get the information from the database using get_posts:

<?php
$gallery = get_post_gallery( get_the_ID(), false );
$args = array( 
    'post_type'      => 'attachment', 
    'posts_per_page' => -1, 
    'post_status'    => 'any', 
    'post__in'       => explode( ',', $gallery['ids'] ) 
); 
$attachments = get_posts( $args );

foreach ( $attachments as $attachment ) {

    $image_alt = get_post_meta( $attachment->ID, '_wp_attachment_image_alt', true);
    if ( empty( $image_alt )) {
        $image_alt = $attachment->post_title;
    }
    if ( empty( $image_alt )) {
        $image_alt = $attachment->post_excerpt;
    }
    $image_title = $attachment->post_title;
    $image_url = wp_get_attachment_image_src( $attachment->ID, 'full' );

    echo '<div class="one-third columns gallery-item">';
    echo '<div class="item-picture" data-type="image">';
    echo '<img src="' . $image_url[0] . '" alt="'. $image_alt .'">' ;
    echo '<div class="image-overlay">';
    echo '<a href="' . $image_url[0] . '" data-rel="prettyPhoto">
          <span class="zoom"></span></a>';
    echo '</div>';
    echo '<span class="item-label">' . $image_title . '</span>';
    echo '</div>';
    echo '</div>';

} ?>

The script looks for alt-tag info in _wp_attachment_image_alt, post_title and post_excerpt until it finds a value.

Leave a Comment