1

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!

  • The answer to this will involve the pre_get_posts filter – Tom J Nowell Jan 5 '15 at 15:57
3

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.

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