Drupal roles : Programatically Adding a role to a user in Drupal 7
20th Jan 2011
Steven Jones
Senior Developer
Hey, you seem to look at this article a lot! Why not Bookmark this article so you can find it easily in the future?
It used to be a bit of a chore to add a role a user in Drupal, but no longer!
All you need to do is this (in Drupal 7):
$uid = 123;// User ID of user that you want to add role to.
$role_name = 'Role to add'; // The name of the role to add.
if ($role = user_role_load_by_name($role_name)) {
user_multiple_role_edit(array($uid), 'add_role', $role->rid);
}
Of course someone can still come along and screw up your code by changing the name of the role, so you might want to use the role ID directly, and not bother with the lookup.