Check if a user is logged in, using Javascript
Editorial Note We may earn a commission when you visit links from this website.

It’s easy to check, if a user is logged in using the WordPress PHP function is_user_logged_in(). But what to do, if you want to check the login-stat using JavaScript?

This quick code tip displays several options you have.

Check the body class

This is by far the easiest and fastest solution available. When logged in, WordPress adds the CSS class “logged-in” to the body tag. This class is not present for guests, so you can get the login state using the following JS code:

// jQuery solution:
var isLoggedIn = jQuery('body').hasClass('logged-in')

// Plain JS:
var isLoggedIn = document.body.classList.contains('logged-in');

Custom Ajax endpoint

Sometimes you might not want to rely on the body class; for example you want to serve the same page from cache for logged-in and guest users. Or your theme (or a plugin) removes the “logged-in” class from the body tag. Or maybe you simply want to get additional details, like the user role and not only the login-state.

In those cases, you cannot inspect the current HTML code to get the required information. But don’t worry, it’s very easy to set up a simple Ajax handler to get the required details in your JS code. This solution requires two parts: First, you create the JS code that calls the Ajax endpoint, and second, you create the actual endpoint in PHP.

var ajaxUrl = '/wp-admin/admin-ajax.php';
var isLoggedIn = false;

// This action-string is used again in the PHP code below!
var checkAction = 'check-user-state'; 
 
jQuery.post(ajaxUrl, { action: checkAction }, function(resp) {
    if (resp && resp.success && resp.data) {
        isLoggedIn = response.data.loggedin;
    }

    // Do anything with the isLoggedIn state:
    // Display a Popup, hide the login form, etc.
});

To make the custom JavaScript code work, you need to also create the corresponding endpoint in PHP. You can place the following PHP code into a custom plugin or add it to your child themes functions.php file:

<?php
// This action-string matches the checkAction in our JS snippet above!
$checkAction = 'check-user-state'; 

add_action( "wp_ajax_$checkAction", 'dm_ajax_check_user_state' );
add_action( "wp_ajax_nopriv_$checkAction", 'dm_ajax_check_user_state' );

function dm_ajax_check_user_state() {
    $data = [
        'loggedin' => is_user_logged_in(),
    ];

    wp_send_json_success( $data );
}

The above Ajax endpoint returns a JSON data object that contains a “loggedin” attribute. You can extend that response by adding the current users user-role, or any other detail you want.