It’s easy to check if the current user is logged in with PHP in WordPress. Simply use is_user_logged_in()
function. However, how to do it with JavaScript?
WordPress uses cookies to track logged in users. However, handling cookies is quite complicated, since WordPress doesn’t use a consistent cookie name for this purpose.
However, there’s a better and a simpler way to check the user status. If your theme has body_class()
in the <body>
tag (actually, all good WordPress themes have to implement this), then you’ll see logged-in users have logged-in
class in the body tag.
Using this understanding, we can check if the current user is logged in with JavaScript simply, like this:
document.body.classList.contains( 'logged-in' );
That’s all!
It’s important to note that, your theme must have body_class()
in the <body>
tag. If you don’t see that, you should add this function yourself, or switch to another theme.