Home > Back-end >  How to sort WP_User_Query by last_name, first_name?
How to sort WP_User_Query by last_name, first_name?

Time:06-13

I'd like to generate a list of my users sorted by last_name, first_name with WP_User_Query. If I just wanted to do last_name I'd do this, but I can't figure out how to do multiple meta keys.

$args  = array(
    'orderby' => 'meta_value',
    'meta_key' => 'last_name',
);
$user_query = new \WP_User_Query( $args );

CodePudding user response:

$args  = array(
    'orderby' => array(
        'first_name_clause' => 'ASC',
        'last_name_clause' => 'ASC',
    ),

    'meta_query' => array(
        'relation' => 'AND',
        'first_name_clause' => array(
            'key' => 'first_name',
            'compare' => 'EXISTS'
        ),
        'last_name_clause' => array(
            'key' => 'last_name',
            'compare' => 'EXISTS'
        )
    )
);

$user_query = new \WP_User_Query( $args );
  • Related