0
votes

I'm trying to implement a way to add multiple roles at once with php and wordpress. See image below.

enter image description here

The way it works is that I can select multiple roles and get their "slugs". Everything works so far and I get the correct role "slug" out. Now the next issue is when I go to php and update the roles for the user. I use a foreach on the array i create with selected roles and use add_role() in this foreach. This foreach however only adds the first role for some reason and skips the others. Any ideas for why it would only use the first role selected even though all data is correct?

This is the array I send to my php: enter image description here

And this would be my php that should update the users role:

$oUser = get_user_by('ID', $_POST['iUserID']);

if(isset($_POST['aRoles']) && !empty($_POST['aRoles'])){

    foreach ($_POST['aRoles'] as $key => $oRole) {
        $oUser->add_role( $oRole );
    }

}

I've tried:

  • Adding sleep to see that maybe the code was running too fast
  • I've made sure that the code does indeed reach inside the foreach
  • Tried manually setting the roles string, no luck.
1
Tried adding a sleep to see that maybe it was running too fast. No luck. Still only first item in array. - Lato
wordpress.stackexchange.com/a/214670: “The add_role() function short-circuits if the role already exists in the database. The workaround in this case is to precede your add_role() call with a remove_role() call that targets the role you are adding” - that is an older thread already, but I remember having a similar issue quite recently. - CBroe
@CBroe Interesting. I've tried preceding the add_role() with a remove_role() and still no luck. Here is exactly what I tried inside my foreach: php $oUser->remove_role( $rolename ); $oUser->add_role( $rolename ); - Lato

1 Answers

0
votes

Oh well. I f*cked up. It has always been working... It's just the way that i was displayin the role. My bad.

I would say that even though I f*cked up, @CBroe came with a very good comment to remove the role before adding it. So I'll mark that as my answer. Thanks to everyone who took a look. MY bad for not looking at the correct spot in the code.