I have custom roles in my setup and I want to be able to automatically change a user’s role thru a function. Say user A has a SUBSCRIBER role, how do I change it to EDITOR? When adding a role we just:
add_role( $role_name , $role_display_name , array( 'read' => true,
'edit_posts' => false,
'delete_posts' => false, ));
How about changing a role? Is there something like:
change_role($old_role, $new_role);
UPDATE:
I think this one will do:
$wp_user_object = new WP_User($current_user->ID);
$wp_user_object->set_role('editor');
See the WP_User class, you can use this to add and remove roles for a user.
Specifically, a user’s role can be modified by creating an instance of the
WP_User
class, and calling theadd_role
,remove_role
orset_role
methods depending on what your requirements are.Example
Removing the subscriber role, then adding the editor role.
The add and remove methods are probably most suited to use cases where users are given multiple roles.
If your aim is to simply switch a role, this is more easily done using the
set_role
method, like so.Hope that helps.
Just note that there is a simpler way to change the user role which is especially helpful when you do not know the current role of the user:
->set_role()
Example:
To extrapolate on t31os’s answer you can slap something like this in your functions file if you want to do this programmatically based on a condition
You can change the role of any user by editing the users profile. No need to add any more code when this option is already built into WordPress.
Or
You could use code to change all current users with the subscriber role to editor:
There’s a WordPress function for that!
I think it is best to use WordPress functions, if and when they are available.
You can use the wp_insert_user() function, where one of the arguments that you will need to provide is the $userdata[‘role’]. In this argument you can specify the role that you want to change the user into.
you have to include the /wp-includes/registration.php, if you use the code as a stand alone script.
Regards
Uwe
You can use wp_update_user. Your code shoud be like this:
I know its a very old Post, but i have found that the roles for users are stored in
wp_usermeta
table with keywp_capabilities
inmeta_key
column.If you want to change the user role you can do it by this simple function.
There is two way to use this function.
If you want to change the role for a single role.
Or if you want to add multi roles to the user, use the roles as array in the second parameter.
Good luck.