December 02 2014

WordPress gallery images get evertyhing

While theming wordpress, the use of native gallery is very handy, but sometimes the Codex does not solve every need. Some of these needs are the attachment ID, href source or image dimensions. That is why we created this piece of code which comes in handy. Down below, an "echo" shows the variables in action.

If you need more data like attachments URL, caption, title, alt or description, you can use this one:

 

$galleryData = get_post_gallery( get_the_ID(), false );
$arrayGalleryIDs = explode("," , $galleryData["ids"]); //Convert a string of ID's to an array

for ($i=0; $i < count($galleryData["src"]); $i++) {
     $attachmentID = $arrayGalleryIDs[$i];
     $attachment = get_post( $attachmentID );
     $attachmentSrc = $attachment->guid;
     $attachmentTitle = $attachment->post_title;
     $attachmentCaption = $attachment->post_excerpt;
     $attachmentAlt = get_post_meta( $attachment->ID, '_wp_attachment_image_alt', true );
     $attachmentDescription = $attachment->post_content;
     $attachmentPermalink = get_permalink( $attachment->ID );

     $attachmentAttributes = wp_get_attachment_image_src( $attachmentID, 'large'); //large is set in function.php 
     $attachmentWidth = $attachmentAttributes[1]; 
     $attachmentHeight = $attachmentAttributes[2]; 

     echo "<a href='" . $attachmentPermalink . "'><img src='" . $attachmentSrc . "' alt='" . $attachmentAlt . "' /></a>";
}

 

We hope this code is useful to your projects. If you have any doubts, please contact us!