Created
March 5, 2013 19:06
-
-
Save victor-falcon/5093148 to your computer and use it in GitHub Desktop.
Load users by Role in Drupal 7
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@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:
(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.