I want to sort the result of get_users()
by last name, first name, user defined fields or whatever.
How can I achieve this while still using get_users()
?
I want to sort the result of get_users()
by last name, first name, user defined fields or whatever.
How can I achieve this while still using get_users()
?
2 Answers
Reset to default 5get_users()
does not allow you to directly sort by whatever you like, but there are ways around it.
The Codex for get_users()
says:
orderby - Sort by 'ID', 'login', 'nicename', 'email', 'url', 'registered', 'display_name', 'post_count', 'include', or 'meta_value' (query must also contain a 'meta_key' - see WP_User_Query).
meta_value
is a very powerful way to go here. If you choose it, you have to define the meta_key
which will then define what to order by.
meta_key - The meta_key in the wp_usermeta table for the meta_value to be returned. See get_userdata() for the possible meta keys.
get_userdata()
can return quite a lot of values, possibly enough to order by.
Examples
So, if you want to order by the users last name for example, use get_users()
like this:
$your_users = get_users('orderby=meta_value&meta_key=last_name');
Order by first name
$your_users = get_users('orderby=meta_value&meta_key=first_name');
Order by registration date
$your_users = get_users('orderby=meta_value&meta_key=user_registered');
You can of course use order
to reverse the sorting order
// Sorting users by registration date - ascending (standard behaviour)
$your_users = get_users('orderby=meta_value&meta_key=user_registered');
// Sorting users by registration date - descending (add order=DESC)
$your_users = get_users('orderby=meta_value&meta_key=user_registered&order=DESC');
One step further
If you want to order by user-defined values, which get_userdata()
won´t deliver, you can pass another parameter to get_users()
.
$your_users = get_users('fields=all_with_meta');
This will result in an array which contains all meta data that is linked to a user. You can then use a custom sort function (via usort()) to order by a specific parameter.
$your_users = get_users('fields=all_with_meta');
// very basic comparison...
function compare($a, $b) { return ($a->special > $b->special) ? -1 : 1; }
usort($your_users, 'compare');
As for the examples:
the mentioned $your_users = get_users('orderby=meta_value&meta_key=user_registered');
will not work, since user_registered is NOT in user_meta table (therefore no meta_key
and no meta_value
) but is in (core) users table, so
get_users('orderby=user_registered')
will do the job.