0

I'm working on a project where I need to query all of the image attachments and then organize them based on the date the post they were attached to was published.

The query below worked well, except that the order from $post_image_query was not being maintained in the output from $the_query.

So my question was how can I query all attachments and order them by the publishing date of their parents?

// 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',
        'post_parent__in' => $post_image_query->posts
    );
);
0

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 :)

| improve this answer | |

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.