使用成员和强大的表单添加角色

时间:2021-09-02 作者:TravelingTartar

不是编码员:-(当有人完成一个强大的表单时,我一直在使用代码片段来更改角色。效果很好。但在另一个网站上,我只想“添加”一个角色。我不知道如何修改下面的代码片段来添加给定的角色,而不是更改它。还有一个想法……一种保护不仅仅是管理员角色的方法。我不知道如何修改“如果”行来保护不仅仅是管理员。有什么想法?

/**
* This will change a user to a different member role after they complete their member profile.
*/
add_action(\'frm_after_create_entry\', \'inactive_to_member\', 20, 2);
function inactive_to_member($entry_id, $form_id){
 if($form_id == 21){ // form id of the form to copy
   $new_role = \'census_club\'; //change this to the role users should be granted upon completing form

   $user = wp_get_current_user(); //get logged in user
   if(!$user) {
       return; //don\'t continue if user doesn\'t exist
   }

   $updated_user = (array)$user;

   // Get the highest/primary role for this user  
   $user_roles = $user->roles;
   $user_role = array_shift($user_roles);
   if ( $user_role == \'administrator\' ) 
       return; //make sure we don\'t downgrade any admins

   $updated_user[\'role\'] = $new_role;
    
   wp_update_user($updated_user);
 }
}```

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

您要使用方法WP\\u User::set\\u role()https://developer.wordpress.org/reference/classes/wp_user/set_role/

如果要将该角色添加为其他角色,请替换set_role 具有add_role

add_action( \'frm_after_create_entry\', \'inactive_to_member\', 20, 2 );
function inactive_to_member($entry_id, $form_id) {
    if ( $form_id == 21 ) { // form id of the form to copy

        $user = wp_get_current_user(); //get logged in user
        if ( !$user ) {
            return; //don\'t continue if user doesn\'t exist
        }

        // Get user roles
        $user_roles = $user->roles;
        // Make sure they\'re not an administrator
        if ( !in_array( \'administrator\', $user_roles ) ) {
            // Make Role Census Club         
            $user->set_role( \'census_club\' );
        }
    }
}

相关推荐