Bulk remove a role from a list of Drupal users

You have a list of users and you want to remove a specific role from their accounts in bulk programatically.

The following snippet can be run in an update hook. When update.php is run, it will remove the administrator role from the list of users defined in the $users array (current example users: user_1, user_2, user_3). If you don't know where to put the update hook, I wrote an article about setting up a deployment module.

What do you change in this snippet?

  • Change the usernames (user_1, user_2, user_3) in $users to the list of usernames you want to bulk update.
  • Change 'administrator' in array_search() to the role you want to remove from the list of users
  • Change the function name, deploy_update_7001(), to the relevant function name for your module

Admin interface

You can do this in the admin interface, but there are times when you might need to do it programmatically. For example, you might need to deploy and test this change before doing it on the live site.

The snippet

The first snippet loads users by user name. The second snippet loads users by user ID. If the user names can change before this code is run, it is advisable to load by user ID (the second snippet) rather than user name.

Using username
function deploy_update_7001() { 
 // Users who have administrator role who should not have it
  $users = array('user_1', 'user_2', 'user_3');
 
  foreach ($users as $username) {
    $user = user_load_by_name($username);
    if (($key = array_search('administrator', $user->roles)) !== false) {
      unset($user->roles[$key]);
    }
    user_save($user);
  }
}

Using user ID
function deployupdate_update_7001() {
  // Users who have administrator role who should not have it
  $users = array(2, 3, 4);
 
  foreach ($users as $userid) {
    $user = user_load($userid);
    if (($key = array_search('administrator', $user->roles)) !== false) {
      unset($user->roles[$key]);
    }
    user_save($user);
  }
}

Add new comment

Plain text

  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.