I’m displaying a gallery image but I also want display the caption for image. I can get the info that we insert when us upload a image in WordPress Dashboard like “Title/Caption/ALT/Description”. I want get anyone and display.
<?php
$gallery = get_post_gallery_images( $post );
foreach( $gallery as $image_url ) :
?>
<div class="item" style="background-image: url('<?php echo $image_url ?>'); background-size: cover">
<div class="caption">
<!-- Here I want display the Title/Caption/ALT/Description of image -->
<h2><?php echo $image_url->"DESCRIPTION/TITLE/ALT"; ?> </h2>
</div>
</div>
Reading at the docs of get_post_gallery_images I didn’t find a solution for my issue.
I also found this answer but I don’t know if it works and I’ve erros to implement in my code.
Anyway, how can I solve this?
2 Answers
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:
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
.