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.

Read More

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',
                    array(
                        'key' => 'contributorid1',
                        'value' => $id,
                        'compare' => '='
                        ),

                    array(
                        'key' => 'contributorid2',
                        'value' => $id,
                        'compare' => '='
                        )
                    )
    );
    $posts = query_posts($args2); 
}

Related posts

Leave a Reply

1 comment

  1. You can do this using WP_Query since 3.1 with a meta_query.

    $args = array(
        'meta_key' => '_count-views_all',
        'orderby' => 'meta_value_num',
        'order' => $sortOrder,
        'posts_per_page' => 9,
        'paged' => $paged,
        'meta_query' => array(
            'relation'  => 'OR'
            array(
                'key'     => 'contributorid1',
                'value'   => $id,
                'compare' => '='
            ),
            array(
                'key'     => 'contributorid2',
                'value'   => $id,
                'compare' => '='
            )
        )
    );
    
    $query = new WP_Query( $args );