jQuery check wordpress_logged_in cookie jQuery check wordpress_logged_in cookie wordpress wordpress

jQuery check wordpress_logged_in cookie


You can't access to wordpress cookies named wordpress_logged_in using js/jquery just because it's flagged as HttpOnly:

A secure cookie is only sent to the server with a encrypted request over the HTTPS protocol... To prevent cross-site scripting (XSS) attacks, HttpOnly cookies are inaccessible to JavaScript's Document.cookie API; they are only sent to the server.

But since 3.0 wordpress add one more cookie named wp-settings-{time}-[UID] when user log in:

WordPress also sets a few wp-settings-{time}-[UID] cookies. The number on the end is your individual user ID from the users database table. This is used to customize your view of admin interface, and possibly also the main site interface.

And you can get this cookie using js/jquery. So, you can even get user ID from cookies.

Here is working js function for getting cookies and checking, if user is logged in:

function getLoggedInCookie() {    var cookie = document.cookie.indexOf('wp-settings-time') !== -1;    if(cookie){        alert('Logged in');    }else{        alert('Not User');    }}getLoggedInCookie();

jQuery solution will be to include Cookie plugin to your wordpress theme/plugin and try to use it( may need in some modifications ).

NOTE:

Provided code will work with login forms, which use standart WordPress functions and endpoints, such as http://{website-name}/wp-admin/ or http://{website-name}/wp-login.php. Third party plugins could not set cookies named wp-settings-{time}-[UID].


If you only want to know if a user is logged in you can check if the body element has class 'logged-in' i.e.

jQuery( 'body' ).hasClass( 'logged-in' )

WordPress adds this class to the body element if a user is logged in.


You can create ajax request to check if user logged in:

in functions.php:

function ajax_check_user_logged_in() {    echo is_user_logged_in()?'yes':'no';    die();}add_action('wp_ajax_is_user_logged_in', 'ajax_check_user_logged_in');add_action('wp_ajax_nopriv_is_user_logged_in', 'ajax_check_user_logged_in');function load_my_scripts(){    wp_localize_script('my-ajax-handle', 'the_ajax_script', array('ajaxurl' => admin_url('admin-ajax.php')));}add_action('wp_enqueue_scripts', 'load_my_scripts');

in js:

var data = {    action: 'is_user_logged_in'};jQuery.post(the_ajax_script.ajaxurl, data, function(response) {    if(response == 'yes') {        // user is logged in    } else {        // user is not logged in    }});