Check if a user is connected and get is ID without fully loading wordpress

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).

error code: 521