I’m writing an advanced cache for WP. I try to make it works with connected users. I want to calculate a user context hash.

To build my hash I need a way to quickly know if the user is logged and get is user ID from advanced-cache.php. So before WP is fully loaded. After with is user ID I can simply do a SQL query to know is role and build the hash with this information.

I read wp_validate_auth_cookie and other related functions without finding how I’m suppose to use that.

1 Answer
1

WordPress stores user_name of logged in user in auth cookie. Auth cookie is signed, so it’s easy to check if it’s fake, so you can trust this info.

OK, so how to get user’s user_name from cookie?

There is function for that 😉

wp_parse_auth_cookie

and this is what it returns:

return compact( 'username', 'expiration', 'token', 'hmac', 'scheme' );

So you can use something like this:

$cookie = wp_parse_auth_cookie( '', 'logged_in' );
$user_name = $cookie['username']

to get user_name of user that is currently logged in.

If you need he’s ID and not user_name, then use DB to retrieve it or change content of the auth cookie (here’s how: Removing username from the ‘wordpress_logged_in’ cookie).

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *