Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call wordpress is_logged_in function from JavaScript

I want to call this function in JavaScript:

http://codex.wordpress.org/Function_Reference/is_user_logged_in

But the examples are only with PHP. When that JavaScript function is called I want to check if the user is logged and send a message / redirect if not.

Is there a way to do this?

like image 778
user2469440 Avatar asked Dec 13 '25 23:12

user2469440


2 Answers

Add this in your functions.php

function check_login() {
    $return['loggedin'] = false;  
    if ( is_user_logged_in() ) {
        $return['loggedin'] = true;    
    }
    echo json_encode($return);
    die();
}
add_action('wp_ajax_check_login', 'check_login');
add_action('wp_ajax_nopriv_check_login', 'check_login');

Add this to your custom JS code

$.ajax({
    url : YOUR_AJAX_URL, // "/wp-admin/admin-ajax.php"
    type : "GET",
    dataType : "json",
    cache : false,
    data : {
        action : 'check_login'
    },
    success : function (json) {
        if (json.loggedin) {
            alert("Loggedin");
        }
    }
});
like image 80
Mithun Sreedharan Avatar answered Dec 16 '25 14:12

Mithun Sreedharan


You can wrap javascript code in between php code like below

<script>
$('#checkLogin').click(function() {
    <?php if (!is_user_logged_in()): ?>
    alert('Please login to access this page');
    location = 'http://www.example.com';
    <?php else: ?>
    alert('You are logged in');
    <?php endif; ?>
});
</script>
like image 43
Manoj Yadav Avatar answered Dec 16 '25 12:12

Manoj Yadav



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!