Re-order posts in query after

For a particular category I needed to merge in another custom post type. Now I would like to resort the query based on a custom field. Is this possible?

Below is the way I’ve merged the queries.

if (in_category( 'Events' ) && is_archive()) {
    global $wp_query;
    $args = array (
        'post_type' => 'custom_post_type'
    );
    $second_query = new WP_Query( $args );
    $wp_query->posts = array_merge( $wp_query->posts, $second_query->posts );
    $wp_query->post_count = $wp_query->post_count + $second_query->post_count;
}

Thanks!

1 Answer
1

Given that meta is cached inside page load it should be reasonably performant to do it like this (not tested):

usort( $wp_query->posts, function ( $post_a, $post_b ) {
    $a = get_post_meta( $post_a->id, 'key', true );
    $b = get_post_meta( $post_b->id, 'key', true );
    if ( $a == $b ) {
        return 0;
    }
    return ( $a < $b ) ? - 1 : 1;
} );

It might be more reasonable to modify query inputs before it’s run though, as per comment.

Leave a Comment