SortUserByLastName
Share Article To

It is very obvious requirement from any client that to list all your website users in alphabetical sort order. My requirement was sort all WordPress users by their last name first and then first name. Tried a lot to get some good result but no luck. Then wrote my own code by getting help from php.net website.


function sort_user_by_name( $a, $b ) {
$retval = strnatcmp( $a->last_name, $b->last_name );
if( !$retval ) {
$retval = strnatcmp( $a->first_name, $b->first_name );
}
return $retval;
}

usort( $user_object, 'sort_user_by_name' );

Explanation: Though the above code is self explanatory let me give a brief idea. `$user_object` is a user object which has all the WordPress users of your website. Now you have to pass this object to PHP in built function usort() as first parameter and in second parameter I have added call back function `sort_user_by_name`. This function will take the user object and try to sort users by their last name first and then by their first name.

Written by 

Leave a Reply

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