Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save jqn/4284b2210ef76572218c73ba7d36a9a9 to your computer and use it in GitHub Desktop.
Save jqn/4284b2210ef76572218c73ba7d36a9a9 to your computer and use it in GitHub Desktop.
Load users by Role in Drupal 7
<?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