Support » Plugins and Hacks » Hacks » Order by meta_key with two meta_queries

Order by meta_key with two meta_queries

  • This should be simple, but I just can’t pinned down a good example of the correct syntax to do this.

    I want to order by the specified meta_key with two meta_queries. The problem is query_posts doesn’t seem to like having two meta_queries with a meta_key. If I take out one of the meta_queries the code works, or if I remove the meta_key and change the orderby to title and leave the meta_queries alone it also works.

    Is there any way to orderby meta_key with two meta_queries?

    $args2 = array(
            'meta_key' => '_count-views_all',
            //'meta_value' => $id,
            'orderby' => 'meta_value_num',
            'order' => $sortOrder,
            'posts_per_page' => 9,
            'paged' => $paged,
            'meta_query' => array(
                        'relation' => 'OR',
                            'key' => 'contributorid1',
                            'value' => $id,
                            'compare' => '='
                            'key' => 'contributorid2',
                            'value' => $id,
                            'compare' => '='
        $posts = query_posts($args2);
Viewing 3 replies - 1 through 3 (of 3 total)
  • Moderator bcworkz


    ‘meta_key’ is not a valid orderby parameter so it ends up being ignored. I can’t explain how it appears to work with a simple meta_query, but you can verify my statement by examining the source code for WP_Query class. You’ll find there are possible, valid SQL queries you just cannot construct through WP query arguments. Fortunately, there are several filters you can hook to directly modify the query to anything you like. The problem is the filters fire for every query, so you’ll need code to distinguish between your special query and all others. Class_Reference/WP_Query#Filters

    The code is not ordering by the meta_key it is order by the value of a meta key which is supported in wordpress.

    The error is not that I can’t orderby the meta the problem is the query_posts function will not allow you to set a meta_key and set two meta_queries.

    You can set a meta_key and one meta_query and everything will work

    Moderator bcworkz


    Yes, the code is, but you asked if you can orderby meta_key. I took it too literally :/ but I understand now. You should be able to do this. You might experimentally try hooking the ‘posts_request’ filter to see how the actual query ended up being constructed, it should give an indication of what’s improperly interpreted, hopefully leading to a workaround.

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Order by meta_key with two meta_queries’ is closed to new replies.
Skip to toolbar