简体   繁体   中英

javascript calling function wordpress is_logged_in

Well, I want to call this function on a 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.

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>

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");
        }
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM