-
-
Save victor-falcon/5093148 to your computer and use it in GitHub Desktop.
<?php | |
/** | |
* Users with role | |
* | |
* @param $role mixed The name or rid of the role we're wanting users to have | |
* @param $active_user boolean Only return active accounts? | |
* | |
* @return array An array of user objects with the role | |
*/ | |
function users_with_role($role, $active_user = TRUE) { | |
$uids = array(); | |
$users = array(); | |
if (is_int($role)) { | |
$my_rid = $role; | |
} | |
else { | |
$role_obj = user_role_load_by_name($role); | |
} | |
$result = db_select('users_roles', 'ur') | |
->fields('ur') | |
->condition('ur.rid', $role_obj->rid, '=') | |
->execute(); | |
foreach ($result as $record) { | |
$uids[] = $record->uid; | |
}; | |
$query = new EntityFieldQuery(); | |
$query->entityCondition('entity_type', 'user') | |
->propertyCondition('uid', $uids, 'IN'); | |
if ($active_user) { | |
$query->propertyCondition('status', 1); | |
} | |
$entities = $query->execute(); | |
if (!empty($entities)) { | |
$users = entity_load('user', array_keys($entities['user'])); | |
} | |
return $users; | |
} |
@victoor Thanks for this guys. Question: I have a user with the role 'authenticated user' but when I change the 'role' from administrator to 'authenticated user' (without the apostrophes) I get NO returned results at all... but if I use administrator as the role value, I DO get results.
I even confirmed in DRUPAL that the user is ACTIVE.
Any ideas what I need to do to get authenticated users returned?
Awesome.
I have a user with the role 'authenticated user' but when I change the 'role' from administrator to 'authenticated user' (without the apostrophes) I get NO returned results at all... but if I use administrator as the role value, I DO get results.
@aameakerisa, the 'authenticated user' role is not tracked in the users_roles table because all registered users are implicitly members of this role. To find all users with the 'authenticated user' role, do this:
$uids = db_select('users', 'u')
->fields('u', array('uid'))
->condition('uid', 0, '!=') // Exclude the Anonymous account.
->execute()->fetchCol();
(The 'anonymous user' role is also not tracked because any user who is not logged in is considered to have the role. The user account with UID 0 is a placeholder used to represent all anonymous users.)
Of course this would be overkill if you just want to check whether the current user is logged in, in this case use user_is_logged_in() instead.
I've tried to improve your code a little bit.
Greetings, mxr576.