在重力提交提交中更改Wordpress用户角色

时间:2018-01-31 20:58:42

标签: php wordpress gravity-forms-plugin

我正在使用Gravityforms和User registration add-on,并且有一个表单,在提交时应该将当前用户的角色更改为没有任何基本条件的新角色。

使用gravity \ forms docs https://docs.gravityforms.com/gform_user_updated/#1-update-user-role并尝试此操作:

add_action( 'gform_user_updated_3', 'change_role', 10, 3 );
function change_role( $user_id, $feed, $entry, $user_pass ) {

    global $current_user;
    get_currentuserinfo();
    $user_id = $current_user->ID;

    echo $user_id;
    if( ! $user_id ) {
        return;
    }
    $user = new WP_User( $user_id );
    $user->set_role( 'role' );     // update 'role' to the name of the desired role

}   

但它不起作用!有没有人知道为什么这是错误的或对代码的任何其他修改?

1 个答案:

答案 0 :(得分:1)

在将代码与Gravity Forms文档进行比较时,我会看到一些代码。

这是您的代码,其中添加了一些评论:

add_action( 'gform_user_updated_3', 'change_role', 10, 3 );

function change_role( $user_id, $feed, $entry, $user_pass ) {

    global $current_user; //  you probably don't need this
    get_currentuserinfo(); // you probably don't need this
    $user_id = $current_user->ID; // $user_id should already be a numeric value passed in to the function containing the logged in user's ID so you shouldn't need to do this. You're resetting the $user_id variable here to whatever is being pulled out of the get_currentuserinfo() function, and I'm guessing that's the problem

    //I would get rid of this echo and if statement
    echo $user_id;
    if( ! $user_id ) {
        return;
    }

    $user = new WP_User( $user_id );
    $user->set_role( 'role' ); // the word "role" here needs to be the role name

}

我认为你可以简化一些。试试这个:

add_action( 'gform_user_updated_3', 'change_role', 10, 3 );

function change_role( $user_id, $feed, $entry, $user_pass ) {

    $user = new WP_User( $user_id );
    $user->set_role( 'new_role_name_here' ); // Add an existing role here to update the user too

}