I have a custom WP_Query with 2 different meta queries. I want to order the results of both queries differently. The first meta_query I want to order by a custom field (high integer - low integer). The second meta_query I want to order by date. To be clear, I want to first show the results from the first query and then the results from the second query. Below the code I currently have. For some reason it is ordering both meta_query by meta_value_num. How can I order both meta queries differently, within the same WP_Query? Or do I actually have to make 2 different WP queries?

$sticky = get_option( 'sticky_posts' );
$term = get_queried_object();
/* Query sticky posts */
$the_query = new WP_Query( array( 'post__in' => $sticky, 'ignore_sticky_posts' => 1, 'posts_per_page' => 5, 'post_type' => 'ads', 'tax_query' => array(
    //Get posts by term slug
    'relation' => 'OR',
        array (
            'taxonomy' => 'ad_cat',
            'field' => 'slug',
            'terms' => $term->slug,
    'meta_query' => array(
   //Get posts with custom field key 'cc_aff_stick_top'
    'relation' => 'OR', 
    'is_aff' => array(
        'key' => 'cc_aff_stick_top',
        'compare' => 'EXISTS',
    //Get posts without key
    'is_not_aff' => array(
        'key' => 'cc_aff_stick_top',
        'compare' => 'NOT EXISTS',
//Order by CF cc_aff_stick_top and otherwise by date
'orderby' => array( 
    'meta_value_num' => 'ASC',
    'date' => 'DESC'
) );
// The Loop
if ( $the_query->have_posts() ) {
  • For the first meta query (is_aff), try adding 'type' => 'NUMERIC' to the array. Then in the orderby, replace the 'meta_value_num' => 'ASC' with 'is_aff' => 'DESC'. – Sally CJ Jan 9 at 13:55
  • Hi, yes i did try that. For some reason it orders the posts that are queried by the first and second meta_query. The 'date' => 'DESC' is simply being ignored. – RobbTe Jan 9 at 14:01
  • Found that i misuse the 'orderby' with multiple 'meta_key's. The second 'orderby' only applies when the queried posts have the same value for the first 'orderby'. – RobbTe Jan 10 at 12:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.