Skip to main content

Drupal roles : Programatically Adding a role to a user in Drupal 7

An article from ComputerMinds - Building with Drupal in the UK since 2005
20th Jan 2011

Steven Jones

Senior Developer
Steven Jones
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.

Hi, thanks for reading

ComputerMinds are the UK’s Drupal specialists with offices in Bristol and Coventry. We offer a range of Drupal services including Consultancy, Development, Training and Support. Whatever your Drupal problem, we can help.