1

get_current_user_id()为以下代码返回 0。我确实尝试了一些堆栈溢出可用的解决方案,但不知何故对我不起作用。我期待解释为什么它返回零以及如何解决?

PS:我从外部 php 页面调用 get_current_user_id() 并包含在内'../wp-blog-header.php'

代码:

<?php
require('../wp-blog-header.php');
get_header();

$user_ID = get_current_user_id(); 
echo $user_ID;

?> 
4

3 回答 3

7

您必须调用用户身份验证的 wordpress 过程。尝试在之前添加以下代码get_current_user_id();,如果它不能解决您的问题,它至少会为您指明正确的方向:

$user_id = apply_filters( 'determine_current_user', false );
wp_set_current_user( $user_id );

希望能帮助到你!

于 2016-03-20T12:36:53.710 回答
1

这可能是wp-blog-header.php直接包含在您的外部文件中的结果。从食典上get_current_user_id()

用户的ID,如果有当前用户;否则为 0。

我不确定您要做什么,但正确的方法是将此逻辑添加到functions.php的正确操作钩子下,或者通过编写自定义插件。通过执行这两件事之一,您将可以访问经过身份验证的用户。

于 2016-03-20T12:18:59.600 回答
0

如果您使用的是 ajax,那么可能在某些浏览器版本中我们无法通过 get_current_user_id() 获取 id,为此我们可以在 ajax 中使用 xhrFields,然后它会正常工作。如果是浏览器版本的问题。

        jQuery.ajax({
            type: "POST",
            xhrFields: {
                withCredentials: true
            },
            cache: false,
于 2019-08-30T13:26:36.703 回答