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?

Read More

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

Related posts

3 comments

  1. 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:

  2. I modified your function:

    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, 'orderby' => 'last_name', 'order' => 'DESC' ) ); 
    
       echo '<ul>';
       foreach ( $members as $member ) {
          echo '<li>' . $member->first_name . ' ' . $member->last_name . '</li>';
       }
       echo '</ul>';
    }
    

    Just added two more parameters two your arguments

  3. Add orderby=>last_name,order=>DESC in your get_users argument.
    Hope this will help you.

    $members = get_users( array( 'meta_key' => 'department', 'meta_value' => $department, 'orderby' => 'last_name', 'order' => 'DESC' ) ); 
    

Comments are closed.