I want to execute custom jquery code which shows login dialog to user if he clicks a button and he is not logged in. How could I do that?
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');