2

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>';
}

2 Answers 2

2

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?

7
  • thanks for this. Where do I put my two user role types though?
    – Claire
    Sep 4, 2012 at 15:59
  • I may not be able to use the get_users function anyway because I need to sort the output by last name, and I have realised that object that get_users returns doesn't have a parameter of last name :( so I can't say orderby=last_name
    – Claire
    Sep 4, 2012 at 16:00
  • 1) The roles from the question are already in the code (line 2). You can edit the 'filter_two_roles' function to get other roles too. 2) You most certainly can sort them by first or last name; I've edited the answer to provide this as well. Sep 4, 2012 at 16:45
  • Wow thank you SO much, that works perfectly. I really am so grateful, I spent about 2 hours at work this afternoon trying to get round this, seen this answer when I got home and couldn't resist trying it. Thank you.
    – Claire
    Sep 4, 2012 at 19:20
  • You're welcome! Glad it worked :) Sep 4, 2012 at 19:51
1

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>';
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.