【问题标题】:Conditionally updating roles in WordPress有条件地更新 WordPress 中的角色
【发布时间】:2014-07-20 22:11:45
【问题描述】:

我实际上想创建一个简单的函数,但它似乎不起作用。
我希望当用户在 Wordpress 上登录到他的帐户以在某些条件下更改他的角色(订阅者 -> 目录_1)(在这种情况下很容易测试,它应该每次都更改,但仍然无法正常工作)。
这是我的代码:

add_action('wp_login', 'update_roles');

function update_roles()
{
   global $wpdb;
   $author = wp_get_current_user();
   if(current_user_can('subscriber'))
   {
       $author->remove_role( 'subscriber' );
       $author->add_role( 'directory_1' );
   }
}

感谢您的帮助!

【问题讨论】:

    标签: wordpress role


    【解决方案1】:

    您应该使用wp_update_user() 来更新用户的角色。使用add_role() 添加角色后,您可以执行以下操作:

    function custom_update_roles( $user_login, $user ) {
    
        if ( ! empty( $user->roles ) && is_array( $user->roles ) ) {
    
            if ( in_array( "subscriber", $user->roles ) ) {
                $user_id = wp_update_user( array( 'ID' => $user->ID, 'role' => 'directory_1' ) );
    
                if ( is_wp_error( $user_id ) ) {
                    // Error.
                } else {
                    // Success.
                }
            } else {
                // This user is not a subscriber.
            }
        }
    }
    add_action( 'wp_login', 'custom_update_roles', 10, 2 );
    

    参考:

    【讨论】:

    • 非常感谢!虽然我现在收到此错误:致命错误:无法重新声明 update_roles()(之前在 functions.php:6 中声明)
    • 仍然报错,但这次是在最后一行。试图理解问题,但似乎无法这样做:/:解析错误:语法错误,第 248 行的 functions.php 中的文件意外结束
    • 我认为该错误可能与我发布的代码无关。你能把你的functions.php代码粘贴到pastebin.com吗?
    • 试试我更新的代码。如果不起作用,请尝试将“订阅者”全部小写。
    • 您是否使用add_role() 函数设置了directory_1 角色?
    猜你喜欢
    • 2012-02-29
    • 2013-09-17
    • 2012-06-10
    • 2015-12-09
    • 2013-07-11
    • 2016-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多