Updated user role inncorrect when using wp_get_current_user()

admin2025-06-03  2

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.

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.

Share Improve this question asked Aug 15, 2018 at 10:23 SwenSwen 1,4047 gold badges22 silver badges37 bronze badges 2
  • 1 $user->roles returns an array, not a single role. – Jos Commented Aug 15, 2018 at 10:57
  • @Jos Yes they both return an array, I just simplified the value in the comments. – Swen Commented Aug 15, 2018 at 11:33
Add a comment  | 

1 Answer 1

Reset to default 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 );
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1748911655a314748.html

最新回复(0)