AnswerBun.com

Update wordpress user roles not working as excepted

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

WordPress Development Asked by Sandy on December 28, 2020

1 Answers

One Answer

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

Add your own answers!

Related Questions

&nbsp not working in comments

1  Asked on December 17, 2021 by wplearner

   

display post pdf attachments in side bar with link text

0  Asked on December 17, 2021 by tdouglassnewby

     

Conditional redirect to several pages

1  Asked on December 17, 2021 by peter-varga

 

the_post_thumbnail doesn’t resize properly

0  Asked on December 17, 2021 by user55555

 

Drop down question

0  Asked on December 17, 2021

       

Prevent private post 404

2  Asked on December 15, 2021 by ben-everard

   

Importing CSV into database table not working?

1  Asked on December 15, 2021 by coder-sathya

       

Display a CPT based on a metabox selection

1  Asked on December 15, 2021 by bigant841

     

advanced custom fields and contact form 7

1  Asked on December 15, 2021 by social

     

Show MySQL errors that occur when I excute $wpdb->insert()

1  Asked on December 15, 2021 by diego-valverde

     

Parent page for CPT

1  Asked on December 12, 2021 by don-munter

 

Ask a Question

Get help from others!

© 2022 AnswerBun.com. All rights reserved.