Home / Admin / Assign User Role Conditionally in WordPress
Duplicate Snippet

Embed Snippet on Your Site

Assign User Role Conditionally in WordPress

This snippet works with WPForms and the User Registration Add-on. It lets you assign user roles conditionally based on form input.

<10
Code Preview
php
<?php
/**
 * Assigns a specific WordPress user role based on the selected value in a WPForms multiple-choice field.
 * 
 * @link https://wpforms.com/how-to-assign-user-roles-conditionally-in-wordpress/
 * 
 * @param array $user_data Array containing user registration data.
 * @param array $fields    Array of form fields and their submitted values.
 * @param array $form_data Array of form metadata, including the form ID.
 *
 * @return array Modified $user_data with the assigned role if a match is found.
 */
function assign_role_during_registration( $user_data, $fields, $form_data ) {
    // The ID of your form and the field used for selecting the role
    $form_id       = '13'; // Replace with your form ID
    $role_field_id = '6'; // Replace with the ID of your "Multiple Choice" field
    // Ensure we're working with the correct form
    if ( $form_data['id'] !== $form_id ) {
       return $user_data;
    }
    // Mapping values from the field to WordPress roles
    $role_mapping = [
       'Student' => 'author',
       'Teacher' => 'editor',
    ];
    // Retrieve the selected value from the field
    $selected_role = isset( $fields[ $role_field_id ]['value'] ) ? $fields[ $role_field_id ]['value'] : '';
    // Check if the selected value exists in the mapping
    if ( array_key_exists( $selected_role, $role_mapping ) ) {
       // Assign the corresponding role to the user
       $user_data['role'] = $role_mapping[ $selected_role ];
    }
    return $user_data;
}
add_filter( 'wpforms_user_registration_process_registration_get_data', 'assign_role_during_registration', 10, 3 );                      

Comments

Add a Comment