Order by first name

I’m trying to order the member list by display_name or first name ASC.
http://sim.is/sim/felagatal-sim/

This doesn’t seem to work. Any pointers out there? :/

$users = get_users(array(
    'role' => 'sm_flagar',
    'orderby' => 'display_name',
    'order' => 'ASC',
));

    foreach ($users as $user) {
        $firstName = get_user_meta($user->ID, 'first_name', true);
        $lastName = get_user_meta($user->ID, 'last_name', true);
            echo '<li><a href="' . $user->user_url . '">' . $firstName . ' ' . $lastName . '</a></li>' . PHP_EOL;
    }

5 Answers
5

Here is my solution

function split_names( $name ) {
    $names = explode( " ", trim( join( " ", $name ) ) );
    $first_name = array_shift( $names );
    $last_name = array_pop( $names );
    $middle_name = join( " ", $names );

    return  array( "first_name" => $first_name, "middle_name" => $middle_name, "last_name" => $last_name );
}

function sort_by_full_name( $arr1, $arr2 ) {
    $arr1 = split_names( $arr1 );
    $arr2 = split_names( $arr2 );
    $retval = strcoll( $arr1['first_name'], $arr2['first_name'] );
    if ( ! $retval ) $retval = strcoll( $arr1['last_name'], $arr2['last_name'] );
    if ( ! $retval ) $retval = strcoll( $arr1['middle_name'], $arr2['middle_name'] );
    return $retval;
}

$users = get_users( array(
    'role' => 'sm_flagar',
    'orderby' => 'display_name',
    'order' => 'ASC'
) );

$user_list = array();

foreach ( $users as $user ) {
    $firstName = get_user_meta( $user->ID, 'first_name', true );
    $lastName = get_user_meta( $user->ID, 'last_name', true );
    $user_list[] = split_names( array( 
            "first_name" => $firstName, 
            "last_name" => $lastName, 
            "url" => $user->user_url 
    ) );
}

usort( $user_list, 'sort_by_full_name' );
setlocale( LC_COLLATE, $locale );
$locale = setlocale( LC_COLLATE, 'is_IS.utf8' );

foreach ( $user_list as $user ) {
        echo '<li><a href="' . $user["url"] . '">' . 
                    $user["first_name"] . ' ' .
                    $user["middle_name"]
                    $user["last_name"] . '</a></li>' . PHP_EOL;
}

Leave a Comment