简体   繁体   中英

Change user role when user registers on WordPress

I'm using the User Registration plugin by WPEverest to build my registration form. My form has a select option for the user to pick their user role - Applicant or Provider. Below is select input.

<form method='post' class='register' data-form-id="57"
              data-enable-strength-password="" data-minimum-password-strength="3"  data-captcha-enabled="">
..
...
    <select data-rules="" data-id="role" name="role" id="role" class="select ur-frontend-field  " required="required" data-label="What is Your Role?" data-allow_clear="true" data-placeholder="">
        <option value="Applicant"  selected='selected'>Applicant</option>
        <option value="Provider" >Provider</option>
    </select>
...
...
</form> 

Here's my hook in functions.php but somehow it doesn't save the user as the role Provider but only as the default role - Applicant.

add_action('user_register', 'update_role');
function update_role($user_id, $meta=array() ) {

   if ( isset( $_POST['role'] ) ) {
       $userdata = array();
       $userdata['ID'] = $user_id;
       $role = htmlspecialchars($_POST['role'], ENT_QUOTES, 'UTF-8');
      
       //Only allow if user role is those we recognize
       if ( $role == 'Applicant' ) {
           $userdata['role'] = 'applicant';
           wp_update_user($userdata);
           
       } else if ( $role == 'Provider') {
            $userdata['role'] = 'provider';
            wp_update_user($userdata);
       }
   }
}

I tested that $_POST['role'] also returns nothing. Anyone knows how to solve this?

I figured it out. I need to call the plugin's hook as below, not the user_register . It's fired under wp-content\plugins\user-registration\includes\frontend\class-ur-frontend-form-handler.php

do_action( 'user_registration_after_register_user_action', self::$valid_form_data, $form_id, $user_id );

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