There are a handful of User Role plugins out there that could help, such as Multiple Roles. I've personally not used it so I can't attest to how well it performs. If you just want a simple function, you will need to make use of the add_role()
function on a WP_User
object.
So, get your User Object however you want:
- If you want to do this to the currently logged in user, use
wp_get_current_user()
.
- If you want to do this by user ID, you can use
get_userdata()
.
- If you want to do this by another user field (username, email, etc. note: ID works here too) use
get_user_by()
To run this for any user that's logged in, you can use something like this:
add_action( 'init', 'add_staff_role_to_subscriber');
function add_staff_role_to_subscriber(){
if( is_user_logged_in() ){
$user = wp_get_current_user();
// If user is a Subscriber with NO other roles
if( $user->roles[0] == 'subscriber' && ! isset( $user->roles[1] ) ){
$user->add_role('staff');
}
}
}
What it does is make sure the current user is logged in, and then gets the WP_User
object for that user. $user->roles
is a single-dimensional array, so you can just make sure that the only role assigned to them is subscriber
and that there is no second $role
in the array by making sure $user->roles[1]
isn't set, or is false.
Once the staff
role is added to the user, the if statement will always be false since $user->roles[1]
will be set to staff
, or if they already have a secondary role it won't effect them.
Note, that in your question you have Subscriber
capitalized, but roles are lowercase in WordPress, so I made staff
lowercase in my code. You may need to make sure the capitalization matches before executing this code.