WordPress Development Asked by Sandy on December 28, 2020
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
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
Correct answer by Az Rieil on December 28, 2020
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP