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?

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){
  if($photo->ID === $post->ID) break;

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

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.


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


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

| improve this answer | |

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!!

| improve this answer | |
  • Please explain how this answers the question. The question specifically asks for new code. – s_ha_dum Jan 17 '13 at 0:37
  • Maybe I misunderstood the question. I was assuming that the user needed to reorder the images by numbering them. – Susan Smith Jan 17 '13 at 1:15
  • Yes, but appears to want to do so programmatically. See toscho's answer. Also, welcome to WPSE. – s_ha_dum Jan 17 '13 at 1:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.