不同角色的WordPress单独注册

时间:2016-08-26 作者:Charles Xavier

当用户单击链接进行注册时,应为其分配不同的角色,而不是默认角色。我尝试过这个链接,但似乎不起作用。我已经把它放在函数中了。php。

Separate registration and login for different roles

我不需要插件,只需要php代码。

例如,如果用户单击此链接,则应自动授予他们卖家角色http://example.com/wp-login.php?action=register&role=seller如果用户单击此链接http://example.com/wp-login.php?action=register它应该为他们提供默认角色。

谢谢

1 个回复
最合适的回答,由SO网友:bynicolas 整理而成

好的,首先你register_form 动作挂钩应用于默认的WP注册表,所以如果不使用它,请记住这一点。

其次add_action 正在调用未知函数。所以很可能这就是它不起作用的原因。

这是正确的代码。添加了带有错误消息的验证。

//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 );

  }
}