如何在登录后更改用户角色?

时间:2019-09-20 作者:Kim Hawley

我在一个批发网站上工作,希望该网站在登录后自动将用户角色从客户更改为批发客户。这将允许批发客户查看批发定价。我已经自定义了这段代码(如下),并将其添加到代码段插件中,但它似乎不起作用。谁能帮我看看我错过了什么?

    function uiwc_change_role()
    {
        // get WP_user object
        $user = wp_get_current_user();
        // if the this is a registered user and this user is not an admin
        if (false !== $user && !user_can($user, \'administrator\')) {
            //set the new role to our customer
            $user->set_role(\'wholesale-customer\');
        }
    }
    add_action(\'wp_login\', \'uiwc_change_role\', 100, 0);  
非常感谢您提供的任何帮助!

1 个回复
SO网友:Jacob Peattie

使用wp_login hook登录的用户可能尚未设置为当前用户,因此使用wp_get_current_user(), 使用传递给挂钩回调的用户对象。然后,您可以确定您正在为正确的用户设置角色,而不是依赖全局状态,这是不可靠的。最好使用通过全局状态传递给回调的参数。

此外,使用user_can() 不鼓励检查角色。内部user_can() 使用$user->has_cap(), 其中包含此注释its documentation:

虽然在一定程度上支持对角色代替功能进行检查,但不鼓励这种做法,因为它可能会产生不可靠的结果。

而是检查$user->roles 对于用户的角色。我也会考虑检查用户是否是客户,而不是管理员。

考虑到这两点,您的代码如下所示:

add_action(
    \'wp_login\',
    function( $user_login, $user ) { // We want $user
        if ( in_array( \'customer\', $user->roles ) ) {
            $user->set_role( \'wholesale-customer\' );
        }
    },
    10,
    2 // Necessary for us to get $user
);
另一件需要考虑的事情是,如果您使用WooCommerce Wholesale Prices 插件,用户角色实际上是wholesale_customer, 使用下划线,而不是破折号。

相关推荐