Skip to content

Sort get_users by last name

Not sure why, but it looks like sorting on last name and first name is not built into the WordPress get_users method. Seems like it would be a pretty basic need, but it’s not there. So, it’s on to PHP to make it happen.

This bit of code assumes that $user_list has already been filled with users by calling the get_users method.

usort($all_users, function($a, $b) {
	return strnatcmp($a->last_name . ', ' . $a->first_name, $b->last_name . ', ' . $b->first_name);
});

Once it’s done, $user_list will be sorted based on lastname and firstname. It’s actually sorting on “lastname, firstname” which should work out the same.

Published inCode Tips

2 Comments

  1. Joseph Cotten Joseph Cotten

    I’m looking into this now; I’m shocked I’ve never noticed before that there’s no way to sort by first_name or last_name in the Users list on the backend.

    To which file would you add your code to get the first and last names to appear in the WP backend? I’m using a child theme.

    • It would probably go into your functions.php file since you’re working with a theme. Not sure what you’d filter on to get this in the right spot though to sort the user list.

Leave a Reply

Your email address will not be published. Required fields are marked *