Wordpress - Check if user is logged in using JQuery
Check the class
attribute for body
: If the theme is using body_class()
the body has a class named logged-in
for users that are logged in. Be aware the function can be used on the element html
too.
Example with jQuery:
if(jQuery('body').hasClass('logged-in')){
// Do something
}
Example with pure JavaScript:
if (document.body.classList.contains('logged-in')) {
// do something
}
You can also just use is_user_logged_in()
as a condition to enqueue or print the script.
In case you want to know if the user is logged in at the current moment. The other answers check if the user is logged in or not when the page loaded not the time when you're running the javascript. The user could have logged in in a seperate tab for instance
Put this in your javascript
var data = {
action: 'is_user_logged_in'
};
jQuery.post(ajaxurl, data, function(response) {
if(response == 'yes') {
// user is logged in, do your stuff here
} else {
// user is not logged in, show login form here
}
});
put this in your 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');
Please add body_class() to your html body
<body <?php body_class(); ?>>
//your html code
</body>
This will add logged-in
for logged user then you can use following jquery code to execute your custom juqery code only for logged user.
if ($('body').hasClass('logged-in')) {
//execute your jquery code.
}