How to remove all users and their content from a specific role programmatically ?
2 Answers
Here are some quick code examples that I have used to add or remove user roles in Drupal 6. This can be very helpful if you are building a module for a specific site that has to manipulate user roles. Using this technique is not the most flexible solution as it limits itself to the roles configured on a specific site (based on role id and role name). However, you could easily add a database table and an administration section and make this more flexible if needed.
Here is an easy way to add a role:
//you will need to enter the uid of the user here, I am just using user 1
$user = user_load(1);
//first we check if the user has the role in question (using the rid of the role)
if (!isset($user->roles[7])) {
//if not we add the role and set the role name based on what is entered
//in the drupal role administration section
$user->roles[7] = 'role name seven';
}
Here is an easy way to remove a role:
//you will need to enter the uid of the user here, I am just using user 1
$user = user_load(1);
//first we check if the user has the first role in question
if (isset($user->roles[8])) {
//if so, we unset the role
unset($user->roles[8]);
$edit = array('roles' => $user->roles);
user_save($user, $edit);
}
Here is an easy way to do a role swap:
//you will need to enter the uid of the user here, I am just using user 1
$user = user_load(1);
//first we check if the user has the first role in question
if (isset($user->roles[8])) {
//if so, we unset the role
unset($user->roles[8]);
//now we check to see if they have the role we want to swap for
if (!isset($user->roles[7])) {
//if not we add this role
$user->roles[7] = 'role name seven';
}
$edit = array('roles' => $user->roles);
user_save($user, $edit);
}
check this link for more info my post How to remove all roles from a user?
You need three things:
All users with a certain role
Call user_delete_multiple on an user list (form the previous step)
Use batch API or Drupal Queue API to do the work and avoid PHP execution time exceed errors. If the total user number is very low you may skip this step, but this means less than 100 users. If this is a task that is going to be done just once in the website lifetime you may call directly, but limit the user list form step 1 to 40 or 50 users, the repeat until are users are deleted.
For the first step you can check this question: Get all users with specific roles using EntityFieldQuery
For the third step you can check the Examples for Developers module, Bastch API submodule: https://api.drupal.org/api/examples/batch_example!batch_example.module/group/batch_example/7