up vote 3 down vote favorite
3
share [g+] share [fb]

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');
link|improve this question

feedback

3 Answers

up vote 5 down vote accepted

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

EDIT: I really should of 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.

link|improve this answer
feedback

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.

link|improve this answer
wp doesn't recognize that function. I got an "undefined function" error. – Joann Dec 1 '10 at 11:42
By the looks of it, wp_insert_user() seems to do the exact same. When you provide an ID, that ID gets updated. No ID is adding new user. Don't really know what the difference between wp_update_user() and wp_insert_user() is, yet. – Coen Jacobs Dec 1 '10 at 11:46
feedback

you have to include the /wp-includes/registration.php, if you use the code as a stand alone script. Regards Uwe

link|improve this answer
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.