Image Gallery Numbers for 3.5

In previous installations of WordPress it was possible to number images in attachment.php using the code below, which was originally provided here. However, I’m finding that this code no longer works as the image numbers are inaccurate.

Is there a new code available?

<?php
global $post;
$ancestors = get_post_ancestors($post->ID);

$photos = get_children(array(
  'post_mime_type' => 'image', 
  'post_parent'    => array_shift($ancestors),
));

$index = 0;
foreach($photos as $photo){
  $index++;
  if($photo->ID === $post->ID) break;
}

printf('%d out of %d', $index, count($photos));
      ?>

Related posts

Leave a Reply

2 comments

  1. There is no complete solution possible. And that is not new.

    Any image can be a part of a gallery in a post that is not that image’s parent. So the post parent is not a useful parameter. The new interface makes such galleries easier to create, but they were possible in earlier versions too.

    Even if the attachment’s parent contains a gallery with that image – there could be another gallery with the same image. Yes, you can create multiple galleries and re-use images.

    What you can do:

    1. Find all posts with galleries.
    2. Find all galleries using that image.
    3. Parse those galleries to detect the order (good luck with random!).
    4. Try to detect from which post the user came to see the current image (sessions?). Maybe she found it per Google.

    Alternative:

    Create an endpoint for post galleries to keep the relation intact. With an URL like …

    example.com/blog/postname/gallery/1/4/
    

    … you would know you are on the fourth attachment for the first gallery that belongs to the post with the slug postname.

  2. The images can be reordered by clicking and dragging to move them around. I wish that the external hyperlink option hadn’t been removed though!!