简体   繁体   中英

wordpress change user primrary role

How do I change the user's primrary role and not capabilities?

I have this but its wrong. This code below only changes the capability and not primrary role. I need to add a code so it changes from current role to another, from subscriber to banned or subscriber to editor.

$u = new WP_User( $user_id );

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

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

click on image link below to se snapshot
屏幕截图1
屏幕截图2

This code adds changes to capabilities and does not alter the primrary role, I wish to change the primrary role from one to another change it.

ust 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:

// Fetch the WP_User object of our user.
$u = new WP_User( 3 );

// Replace the current role with 'editor' role
$u->set_role( 'editor' );

Note: Remember that set_role will remove the previous roles of the user and assign the new role.

Try set_role , it will remove the previous role, and assign the new one to the user

// Get user id.
$u = new WP_User( 1 );

// Replace role to banned
$u->set_role( 'banned' );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM