Gallerys aren’t implemented the way you’re pulling in images, the images in a gallery might not be attached to the post at all.
get_attached_media
will give you the images attached to the post by the order of their ID.
This means:
- Images you added to the post, then deleted will be in this array
- Images in galleries attached to other posts won’t be in this array
If we think it through logically, if your post had 2 galleries, each with the same photos but ordered differently, how would that work? Which order is correct? Neither. This function has nothing to do with Galleries
So What Are Galleries Then?
Shortcodes/Blocks.
E.g. shortcode:
Or block:
<!-- wp:gallery {"ids":[36,30,22,15,14]} -->
<figure class="wp-block-gallery columns-3 is-cropped"><ul class="blocks-gallery-grid"><li class="blocks-gallery-item"><figure><img src="http://one.wordpress.test/wp-content/uploads/2020/03/be.png" alt="" data-id="36" data-full-url="http://one.wordpress.test/wp-content/uploads/2020/03/be.png" data-link="http://one.wordpress.test/be/" class="wp-image-36"/></figure></li>...etc...</ul></figure>
<!-- /wp:gallery -->
The order of the IDs in the attributes is what determines the order. Using get_attached_media
to try to recreate a gallery in content is a dead end that will not work. You need to look at the shortcode/block instead