Can I pass two roles to the function get_users?

I want to get the users of role academic and student. I have tried using the code below (passing an array of roles, but all users are being displayed, so clearly it’s not working.

$roles=array('academic','student');
$args =array('role'=>$roles);
$users=get_users( $args );

foreach ($users as $user) {
    echo '<li>' . $user->user_email . '</li>';
}

Related posts

Leave a Reply

2 comments

  1. I don’t think it’s possible to do it with the get_users function. From what the Codex implies, you cannot pass arrays to the role argument. But it should be fairly easy to code your way out of that limitation.

    Try this:

    function filter_two_roles($user) {
        $roles = array('academic','student');
        return in_array($user->roles[0], $roles);
    }
    
    $users = get_users('fields=all_with_meta');
    // Sort by last name
    usort($users, create_function('$a, $b', 'if($a->last_name == $b->last_name) { return 0;} return ($a->last_name > $b->last_name) ? 1 : -1;'));
    // Iterate through users, filtering out the ones which don't have the roles we want 
    foreach(array_filter($users, 'filter_two_roles') as $user) {
        // Your code
    }
    

    Asking for users with the argument field=all_with_meta is very powerful, and WP seems to map indexes which aren’t even shown when doing a print_r on the user object. That is why we can sort them using first or last names, as shown above (I actually took the code from an older answer of mine).

    Let us know how it goes?

  2. loop through the roles and merge the results…
    this will work with any number of roles.

    $roles = array('academic','student');
    $users = array();
    foreach ($roles as $role) {
        $args = array('role'=>$role);
        $usersofrole = get_users($args);
        $users = array_merge($usersofrole,$users);
    }
    
    foreach ($users as $user) {
        echo '<li>' . $user->user_email . '</li>';
    }