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);
}
Helpful? Let me know.