Query All Attachments and Order by Parent Publish Date

After spending some time reading the documentation for WP_Query’s Order & Orderby Parameters I found the following listed parameter to almost get me there:

‘post__in’ – Preserve post ID order given in the post__in array
(available since Version 3.5).

Unfortunately I wasn’t using post__in but rather post_parent__in so ordering by post__in didn’t work.

It wasn’t listed in the documentation, but I decided to try and order by post_parent__in and was happy to find out that it worked!

The final result:

// Get All Post IDs
$post_image_query = new WP_Query( 
    array( 
        'post_type' => 'post', 
        'posts_per_page' => -1,
        'orderby' => 'date',
        'fields' => 'ids'
    ) 
);

// Get All Attachments of Posts from $post_image_query 
$the_query = new WP_Query( 
    array(
        'post_type' => 'attachment',
        'post_status' => 'inherit',
        'orderby' => 'post_parent__in',
        'post_parent__in' => $post_image_query->posts
    );
);

This may have been a natural troubleshooting thought to other people, but I was getting close to asking a question here about it because I had no idea how to make it happen 🙂