wordpress separate registration for different roles

Ok, first you the register_form action hook is applied to the default WP registration form, so keep this in mind if you don’t use that.

Secondly, the add_action is calling an unknown function. So most likely this is why it’s not working.

So here’s the corrected code. With added validation with error messages.

//create a hidden field for role
add_action('register_form','wpse_add_hidden_role_field');
  function wpse_add_hidden_role_field(){
    if ( isset( $_GET[ 'role' ] ) ){
      echo '<input id="user_role" type="hidden" tabindex="20" size="25" value="' . $_GET[ 'role' ] . '" name="role"/>';
  }
}


//validate we have permitted roles if not, don't allow subscription
add_filter( 'registration_errors', 'wpse_role_check' );
function wpse_role_check( $errors ){

  if( isset( $_POST[ 'role' ] ) ) {

    //only allow registration if roles are in this array.
    $permitted_roles = array(
        'buyer',
        'seller',
    );

    if( ! in_array( $_POST[ 'role' ], $permitted_roles ) ){

        $errors->add( 'role_not_allowed', __( '<strong>ERROR</strong>: This registration is not allowed.', 'my_textdomain' ) );

    }

  }

  // Else disallow public registration (i.e. no role query string found )
  // If you don't take this into account, anyone can register as subscribers
  else {

    $errors->add( 'public_not_allowed', __( '<strong>ERROR</strong>: Public registration is not allowed.', 'my_textdomain' ) );

  }

  return $errors;

}

//update user profile that have passed registration validation
add_action('user_register', 'wpse_update_role');
function wpse_update_role( $user_id ) {
  if ( isset( $_POST[ 'role' ] ) ){
    $userdata = array();
    $userdata[ 'ID' ] = $user_id;
    $userdata[ 'role' ] = $_POST[ 'role' ];

    wp_update_user( $userdata );

  }
} 

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)