user1384107
user1384107

Reputation: 19

Wordpress - $query, how to order users by lastname

I am trying to change a query that gets users from the db and orders by user_nicename. I would like to sort the order of the users by surname. I have tried changing the ORDER BY the meta data value of last_name, but this didn't work.

Here is the current bit of code that I am trying to change:

    global $wpdb;
$query = "SELECT ID, user_nicename from $wpdb->users ORDER BY user_nicename";
$author_ids = $wpdb->get_results($query);

Any tips or help would be greatly appreciated. I am new to PHP and and learning, but have found myself stumped by this problem.

Many thanks

Upvotes: 0

Views: 1198

Answers (1)

Abhineet Verma
Abhineet Verma

Reputation: 1028

This will enable you to retrieve users orderby their lastname.

$args  = array(
    'meta_key' => 'last_name',
);

$wp_user_query = new WP_User_Query($args);
$wp_user_query->query_orderby = str_replace( 'user_login', 'wp_usermeta.meta_value', $wp_user_query->query_orderby );
$wp_user_query->query();

$users = $wp_user_query->get_results();

Upvotes: 1

Related Questions