How to order users alphabetically by their last name?

I use the following shortcode and function to display members of some departments:

add_shortcode( 'list_of_members', 'members_listing' );
/* usage: [list_of_members department="psychology"] */

function members_listing( $department ) {

    $members = get_users( array( 'meta_key' => 'department', 'meta_value' => $department ) ); 

    echo '<ul>';
    foreach ( $members as $member ) {
        echo '<li>' . $member->first_name . ' ' . $member->last_name . '</li>';
    }
    echo '</ul>';
}

I’d like to order the users alphabetically by last_name. How can I do this?

I was inspired by this question/answer, but I do not understand it completely.

3 Answers
3

Why don’t use built-in functionality of PHP?

Put the following line right before the foreach:

usort($members, create_function('$a, $b', 'return strnatcasecmp($a->last_name, $b->last_name);'));

References:

  • usort
  • create_function
  • strnatcasecmp

Leave a Comment