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
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0