For years, I had 2 user roles on my site: school_user, and theatre_user. Now, I have needed to add a 3rd user role: facilitator_user. This is no problem - I have a custom registration form for each type of user. However, users can be both a theatre_user and a facilitator_user. I have an edit-profile page where the user can update their own information. Is there a way to add an option to the Edit User form so that they can add a secondary role themselves? I have too many users to go back over old records and manually assign them new permissions.
Hi, there's no built-in support for multiple User roles in Forms, but you could use the Forms API and some custom code to do something similar. You could add a generic select field that contains options for each secondary role. The value of each option should equal the slug of the role (see some example role slugs in role-slugs.png, and see an example generic field in generic-select.png). Then use the following custom code snippet as a guide for creating your own custom solution:
add_action('cred_save_data', 'tssupp_add_secondary_role_forms',10,2);
function tssupp_add_secondary_role_forms($post_id, $form_data)
{
$role_slug = 'your-generic-field-slug';
$forms = array( 12345 );
// do not edit below this line
if ( in_array($form_data['id'], $forms) )
{
$user_id = get_current_user_id();
$secondary_role = isset($_POST[$role_slug]) ? $_POST[$role_slug] : null;
if(!$user_id || !$secondary_role)
return;
$user = new WP_User($user_id);
$user->add_role($_POST[$role_slug]);
return;
}
}
You would replace your-generic-field-slug with the slug of your generic select field, and replace 12345 with the numeric ID of your Edit User Form, or a comma-separated list of numeric IDs if you want to apply this code to multiple Edit User Forms with similar fields.
Reference:
https://toolset.com/forums/topic/adding-a-secondary-role-to-a-wordpress-user/#post-607852