How to get gallery images?

I have some images uploaded in wordpress posts (eg. post#1, and post#2). Now I’ve created a new post (eg. Post#3), and in this post I have inserted the WordPress 3.5 gallery, I did not upload any image in the post#3, instead I used the images from the post#1 and post#2.
Now in the post#3, I would like to get the links to the images, but I can not seem to get. I am using the following code:

$attachments = get_children( array('post_parent' => get_the_ID(), 'post_type' => 'attachment', 'post_mime_type' =>'image') );
    foreach ( $attachments as $attachment_id => $attachment ) {
            echo wp_get_attachment_image( $attachment_id, 'medium' );
   }

It will show only the image if I upload in the post, but it won’t show the image if I add from the other posts. So, how can I get the links to the images which are added in the gallery but not uploaded.

Thanks for any help.

4 Answers
4

I had the same problem – how can I display all the images from a post containing a gallery where some of the images are not attached to the post, or are attached to different posts?

The new media interface in WP3.5 allows you to add any of the images in the media library to a gallery, regardless of whether they are “attached” or not. As you’ve discovered, the “get_children” function only returns images that are attached to the post. The trick I used is to get the ids from the shortcode itself rather than from the fact that they are attachments. The shortcode includes all of the image ids, regardless of whether they are attached to the post or not. E.g. . Obviously, wordpress can parse this to retrieve all the images and display them in a gallery format using the “gallery_shortcode” function included in the core of wordpress (in includes/media.php). To get the ids of all images in the short code I made a new function in my functions.php file:

function grab_ids_from_gallery() {

global $post;
$attachment_ids = array();
$pattern = get_shortcode_regex();
$ids = array();

if (preg_match_all( "https://wordpress.stackexchange.com/". $pattern .'/s', $post->post_content, $matches ) ) {   //finds the     "gallery" shortcode and puts the image ids in an associative array at $matches[3]
$count=count($matches[3]);      //in case there is more than one gallery in the post.
for ($i = 0; $i < $count; $i++){
    $atts = shortcode_parse_atts( $matches[3][$i] );
    if ( isset( $atts['ids'] ) ){
    $attachment_ids = explode( ',', $atts['ids'] );
    $ids = array_merge($ids, $attachment_ids);
    }
}
}
  return $ids;

 }
add_action( 'wp', 'grab_ids_from_gallery' );

Now just use the “grab_ids_from_gallery()” function to return all the ids as an array in your template.

I’m sure there is a more elegant way to do this – But this works for me. The basis for this code came from:

http://core.trac.wordpress.org/ticket/22960

which discusses this issue.

Leave a Comment