2

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

                    array(
                        'key' => 'contributorid2',
                        'value' => $id,
                        'compare' => '='
                        )
                    )
    );
    $posts = query_posts($args2); 
}
  • 1
    I would avoid using query_posts() unless you have a real good reason to... – Joseph Leedy Jan 7 '13 at 16:24
  • I know, I have to use it for this piece until I rewrite everything to use WP_query. – Christopher Jan 7 '13 at 19:25
  • Does anyone have any other suggestions or is it just not possible? – Christopher Jan 11 '13 at 19:13
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 );

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.