Updated user role inncorrect when using wp_get_current_user()

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.

Answers 1

  • 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 );

Related Questions