0

I ran into an issue with updating a user role, and then checking the current role somewhere later in the code.

After an entire day of debugging, and a night's rest, I figured it out by chance.

See the example below:

// Get current user object
$user = wp_get_current_user();  

// Set new role
$user->remove_role( 'member_pending' );
$user->add_role( 'member' );

// ... Later in another function

// Trying to get the updated role
$user = wp_get_current_user(); 
$role = $user->roles; // Returns "member_pending"

// Going through another hoop to get the role
$user = get_user_by('ID', wp_get_current_user()->ID);
$role = $user->roles; // Return the correct role "member"

I've also tried using wp_cache_flush() before using wp_get_current_user()->roles, but it still shows the incorrect role.

Like I said I already figured out how to "fix" this, but since I spent an entire day troubleshooting this issue, I want to actually understand why it happens.

  • 1
    $user->roles returns an array, not a single role. – Jos Aug 15 '18 at 10:57
  • @Jos Yes they both return an array, I just simplified the value in the comments. – Swen Aug 15 '18 at 11:33
0

Stumbled upon this same issue again, here's how to fix it.

For some reason, you cannot use wp_get_current_user(), as the data is not updated until a refresh happens.

So instead, you use get_user_by().

// The updated current user
$updated_current_user = get_user_by( 'ID', wp_get_current_user()->ID );
| improve this answer | |

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.