最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

php - How to call wordpress is_logged_in function from JavaScript - Stack Overflow

programmeradmin0浏览0评论

I want to call this function in JavaScript:

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?

I want to call this function in JavaScript:

http://codex.wordpress/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?

Share Improve this question edited Aug 1, 2022 at 20:52 TylerH 21.1k77 gold badges79 silver badges112 bronze badges asked Jun 23, 2013 at 19:56 user2469440user2469440 291 silver badge6 bronze badges 0
Add a ment  | 

2 Answers 2

Reset to default 5

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

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.';
    <?php else: ?>
    alert('You are logged in');
    <?php endif; ?>
});
</script>
发布评论

评论列表(0)

  1. 暂无评论