0

I have issues when trying to update or set new user role from an array returned by external API :

// array of roles 
$roles = array("student", "pro" .... );
// get user data
$user = get_user_by("id", 35);
// Append new roles to this user
foreach($roles as $role){
    $new_role = add_role( strtolower($role), $role, []);
    $user->set_role($role);
}

When i check user details after:

print_r($user);

WP_User Object
(
    [data] => stdClass Object
    (
        [ID] => 35
        [user_login] => myuser
        [user_pass] => $P$BoITs3rmyN5w47.gPi9hwzs2TqFhse1
        [user_nicename] => myuser
        [user_email] => 
        [user_url] => 
        [user_registered] => 2020-07-29 11:33:59
        [user_activation_key] => 
        [user_status] => 0
        [display_name] => myuser
        [user_level] => 0
    )

[ID] => 35
[caps] => Array
    (
        [student] => 1
        [pro] => 1
    )

[cap_key] => yyOIY_capabilities
[roles] => Array
    (
    )

[allcaps] => Array
    (
        [student] => 1
        [pro] => 1
    )

[filter] => 
[site_id:WP_User:private] => 1

)

So, why add_role(...) adds caps rather than roles?

Thank you

0

Its better to register this role with add_role ( docs ) before adding it to user

Also, if you want to change roles attribute, try set_role instead of add_role

1
  • Hi, thanks for your comment, i tried but always same issue, i updated my post above – Sandy Jul 29 '20 at 13:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.