I'm making a special child theme template I'm going to use to match custom roles to a user's subscription. So, this is going to be for admin-only maintenance use.
I made a function where I pass the user object, the new role (determined elsewhere), and the present role(s) for that user.
On this site, we require that each user have only one role.
Here is my "role removal" function. variables: $user is the user object for one user. $this_role is the new role I want to assign the user. $user_roles is the array of all roles for that user.
/*
* This function sets the current user to the role specified, and removes all other roles.
* It is true that multiple roles are allowed, but for the purposes of this website, multiple roles
* is not a desirable thing.
*/
function changeRole($user,$this_role,$user_roles){
if(! in_array($this_role,$user_roles) && ! in_array("administrator",$user_roles)){
// If this user currently does not have the correct role, set it here.
$user->set_role( $this_role );
}
foreach($user_roles as $role){
if($role !== $this_role){
// Delete all incorrect roles here.
$user->remove_role( $role ); // <- Gives me an error
}
}
}
The error I'm getting is Uncaught Error: Call to undefined method stdClass::remove_role()
UPDATE
With some more detailed development, I got it to work. I don't know if there was any hope for the WordPress remove_role and add_role, but I found an example using the UM class. This requires Ultimate Member, of course, so it's not a "pure" WP solution. Does work well, though.
This code works:
function changeRole($user,$this_role,$user_roles){
if( ! in_array("administrator",$user_roles) ){
if( ! in_array($this_role,$user_roles) || ( count($user_roles) > 1 ) ){
// If this user currently does not have the correct role, set it here.
//$user->set_role( $this_role ); // OLD
$new_roles_array = array();
foreach($user_roles as $role){
if($role !== $this_role){
UM()->roles()->remove_role( $user->ID, $role ); // NEW
$new_roles_array = array_diff($user_roles, [$role]);
}
}
if( count($new_roles_array) == 0 || isset($new_roles_array[0]) && $new_roles_array[0] !== $this_role ){
UM()->roles()->set_role( $user->ID, $this_role ); // NEW
}
}
}
}
In retrospect, I accepted @bob as the correct answer because I realize that when I performed the get_users
operation, I did not set all fields for the user object:
$users = get_users( array( 'fields' => array( 'ID','user_login' ) ) );
It's possible this was the problem, where an object with minimal proprties was passed to the changeRole function.