Sort users in get_users() in custom order

There is a simpler, faster method than the one by @Warface. This is an extention to @SyHolloway

The concept here is to wrap get_users() in a new function in which you can sort the result from get_users() by the include parameter using usort and then return the resulted array sorted by include

This function does not make provision for the fields argument to be used when the include parameter has been set. all is the only value that will work. You can extent the function to make it work with the other values of the fields parameter when include is in use. Otherwise, if include is not set, the fields parameter works as normal.

Naturally, orderby and order will not work when include is used

This new function operates and is used in exactly the same way as get_users(), except for the above mentioned rules

Here is the function

function get_users_by_include( $args = array() ) {
    $blogusers = get_users( $args );

    if( isset( $args['include'] ) ){
        $include = $args['include'];
        usort($blogusers, function ($a, $b) use( $include ){
            $q = array_flip( $include ); 
            return $q[$a->ID] - $q[$b->ID];
        });
    }

    return $blogusers;
}

You can now use this in your template as follows

$users = get_users_by_include(array( 'include' => array(2,5,1,10,45,32,66) ) );
foreach ( $users as $user ) {
    echo $user->ID . '</br>';
}

Leave a Comment