Give Users More Than One Role
Adds "Additional roles" checkboxes to the user edit screen so an administrator can give someone a second role, for example Editor plus Shop Manager.
Opens WPIDE on
Code
add_action( 'edit_user_profile', function ( $user ) {
if ( ! current_user_can( 'promote_user', $user->ID ) ) {
return;
}
$roles = get_editable_roles();
$primary = reset( $user->roles );
unset( $roles['administrator'], $roles[ $primary ] );
if ( ! $roles ) {
return;
}
wp_nonce_field( 'wpide_extra_roles_' . $user->ID, 'wpide_extra_roles_nonce' );
echo '<h2>Additional roles</h2><table class="form-table" role="presentation"><tr><th scope="row">Also give this user</th><td><fieldset><legend class="screen-reader-text">Additional roles</legend>';
foreach ( $roles as $role => $details ) {
printf(
'<label><input type="checkbox" name="wpide_extra_roles[]" value="%1$s" %2$s> %3$s</label><br>',
esc_attr( $role ),
checked( in_array( $role, (array) $user->roles, true ), true, false ),
esc_html( translate_user_role( $details['name'] ) )
);
}
echo '<p class="description">The main role is chosen in the Role menu above.</p></fieldset></td></tr></table>';
} );
// profile_update runs after WordPress has saved the main role.
add_action( 'profile_update', function ( $user_id ) {
if ( ! isset( $_POST['wpide_extra_roles_nonce'] ) || ! wp_verify_nonce( sanitize_key( $_POST['wpide_extra_roles_nonce'] ), 'wpide_extra_roles_' . $user_id ) ) {
return;
}
if ( ! current_user_can( 'promote_user', $user_id ) ) {
return;
}
$user = get_userdata( $user_id );
$roles = get_editable_roles();
$primary = reset( $user->roles );
$selected = isset( $_POST['wpide_extra_roles'] ) ? array_map( 'sanitize_key', (array) wp_unslash( $_POST['wpide_extra_roles'] ) ) : array();
unset( $roles['administrator'], $roles[ $primary ] );
foreach ( array_keys( $roles ) as $role ) {
$has = in_array( $role, (array) $user->roles, true );
if ( in_array( $role, $selected, true ) && ! $has ) {
$user->add_role( $role );
} elseif ( ! in_array( $role, $selected, true ) && $has ) {
$user->remove_role( $role );
}
}
} );
Notes
Only roles the current user may assign are offered, and the Administrator role is never offered as an extra role.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.