How to change a user’s role?

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');

9

See the WP_User class, you can use this to add and remove roles for a user.

EDIT: I really should have provided more information with this answer initially, so i’m adding more information below.

More specifically, a user’s role can be set by creating an instance of the WP_user class, and calling the add_role() or remove_role() methods.

Example

Change a subscribers role to editor

// NOTE: Of course change 3 to the appropriate user ID
$u = new WP_User( 3 );

// Remove role
$u->remove_role( 'subscriber' );

// Add role
$u->add_role( 'editor' );

Hopefully that’s more helpful than my initial response, which wasn’t necessarily as helpful.

Leave a Comment