How I can get image description/title/alt for gallery image?

You need to get the metadata of each image, add this to your functions.php file:

function get_post_gallery_images_with_info($postvar = NULL) {
    if(!isset($postvar)){
        global $post;
        $postvar = $post;//if the param wasnt sent
    }


    $post_content = $postvar->post_content;
    preg_match('/\[gallery.*ids=.(.*).\]/', $post_content, $ids);
    $images_id = explode(",", $ids[1]); //we get the list of IDs of the gallery as an Array


    $image_gallery_with_info = array();
    //we get the info for each ID
    foreach ($images_id as $image_id) {
        $attachment = get_post($image_id);
        array_push($image_gallery_with_info, 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
                )
        );
    }
    return $image_gallery_with_info;
}

use it in your logic like this:

<?php    
    $gallery = get_post_gallery_images_with_info($post); //you can use it without params too
    foreach( $gallery as $image_obj ) :    
?>                                

    <div class="item" style="background-image: url('<?php echo $image_obj['src'] ?>'); background-size: cover">
        <div class="caption">                
            <!-- Here I want display the Title/Caption/ALT/Description of image -->
            <h2><?php echo $image_obj['title']." ". $image_obj['caption']." ".$image_obj['description']; ?> </h2>
        </div>                                        
    </div>
<?php    
endforeach;
?>

it will output like this:

enter image description here

each image returned by the function is an array like this:

Array
        (
            [alt] => Alt Coffe
             => Caption coffe
            How I can get image description/title/alt for gallery image? => Description coffe
            [href] => http://yoursite/2017/02/14/hello-world/coffee/
            [src] => http://yoursite/wp-content/uploads/sites/4/2017/02/coffee.jpg
            How I can get image description/title/alt for gallery image? => coffee
        )

notice href and src are different, one is the permalink and the other the direct URL.

Leave a Comment