0

I've got the following WP_USER_QUERY in WordPress:

$args = array(
    'orderby'=>'meta_value',
    'meta_query' => array (
        0 => array(
                    'key' => 'last_name',
                    'value' => 'smith'
                    ),
        1 => array(
                    'key' => 'first_name' 
                    )
        ),

        );

$user_query = new WP_User_Query($args);

It's working in as much as it's returning the records I'm expecting it to, but the orderby is off - it's only sorting by their last name, and ignoring the first. How do I search by multiple custom user meta fields in this sort of query?

1

You can do it with 'orderby' parameter. Parameter description:

Field(s) to sort the retrieved users by. May be a single value, an array of values, or a multi-dimensional array with fields as keys and orders ('ASC' or 'DESC') as values. Accepted values are 'ID', 'display_name' (or 'name'), 'include', 'user_login' (or 'login'), 'login__in', 'user_nicename' (or 'nicename'), 'nicename__in', 'user_email (or 'email'), 'user_url' (or 'url'), 'user_registered' (or 'registered'), 'post_count', 'meta_value', 'meta_value_num', the value of $meta_key, or an array key of $meta_query. To use 'meta_value' or 'meta_value_num', $meta_key must be also be defined. Default 'user_login'.

Example:

$args = array(
    'orderby' => array(
        'user_rate' => 'DESC',
        'user_cat' => 'DESC',
    ),
    'meta_query' => array(
        'relation' => 'AND',
        'user_rate' => array(
            'key' => 'user_rate',
            'compare' => 'EXISTS'
        ),
        'user_cat' => array(
            'key' => 'user_cat',
            'value' => $_GET['cat']
        )
    )
);
$user_query = new WP_User_Query($args);
0

Short answer: you can't. I had to write a custom query.

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.