fbpx Drupal roles : Programatically Adding a role to a user in Drupal 7 | ComputerMinds Skip to main content

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

An article from ComputerMinds - A leading UK Drupal development agency since 2005
20th Jan 2011

Steven Jones

Senior Developer

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.