我在 Wordpress 中遇到一个问题,AJAX 调用有时无法检测到用户已登录。在主题的 index.php 文件末尾,我有以下代码:
<?php
$user_id = get_current_user_id();
?>
<script>
alert("Logged in as user #<?php echo $user_id; ?>");
</script>
因此,如果您是已登录并访问该页面的用户,您将收到显示您的用户 ID 的警报。这很好用。
但是,当我通过 admin-ajax.php 执行 AJAX 调用时,它有时不会检测到用户已登录。这是我稍后在 index.php 中执行 ajax 调用的内容(使用 jQuery ajax) :
$.ajax({
url: ajaxUrl,
type: "post",
data: {
action: 'test_ajax'
},
beforeSend: function(){},
complete: function(){},
success: function(data){
alert(data);
},
error: function(){}
});
在我的 functions.php 中:
add_action('wp_ajax_test_ajax', 'test_ajax');
function test_ajax() {
$user_id = get_current_user_id();
echo "Your user id is: ".$user_id;
exit();
}
我注意到有时 wp_ajax 甚至不会运行,所以它会回显 0。所以我添加了 nopriv:
add_action('wp_ajax_nopriv_test_ajax', 'test_ajax');
但即使在运行时,它仍会认为用户未登录,get_current_user_id() 将返回 0。
我也试过 wp_get_current_user();和 global $current_user;,但它们也返回空用户,即没有用户登录。
我不确定这里发生了什么,因为 index.php 中的 get_current_user_id() 有效,但有时 admin-ajax 不这么认为(并非所有时间,有时 - 我无法弄清楚为什么这太断断续续了……)。不过,我注意到这是有效的,但我也不确定为什么:
- 登录 Wordpress
- 转到 index.php。
- 您将收到第一个提示您已登录的提示,但第二个提示(来自 admin-ajax) 另有说法。
- 转到/wp-admin。由于您已经登录,因此无需再次登录即可看到您的仪表板。
- 返回 index.php。现在这两个警报都是正确的。
最佳答案
试试这个让我知道:
<?php
add_action('wp_ajax_test_ajax', 'test_ajax');
function test_ajax() {
global $current_user;
$user_id = get_current_user_id();
echo "Your user id is: ".$user_id;
exit();
}
?>
关于ajax - Wordpress 管理员/ajax 未检测到用户已登录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23638961/