get_current_user_id() 返回零 0
get_current_user_id() returning Zero 0
get_current_user_id()
为以下代码返回 0。我确实尝试了一些可用于堆栈溢出的解决方案,但不知何故对我不起作用。我期待解释为什么它返回零以及如何修复?
P.S:我从外部 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;
?>
这可能是直接在外部文件中包含 wp-blog-header.php
的结果。来自 the Codex on get_current_user_id()
:
The user's ID, if there is a current user; otherwise 0.
我不确定您要做什么,但正确的方法是将此逻辑添加到正确的 [=14] 下的 functions.php =].通过执行这两件事之一,您将可以访问经过身份验证的用户。
你必须调用wordpress的用户认证过程。尝试在 get_current_user_id();
之前添加以下代码,如果它不能解决您的问题,它至少会为您指明正确的方向:
$user_id = apply_filters( 'determine_current_user', false );
wp_set_current_user( $user_id );
希望对您有所帮助!
如果您使用的是 ajax 那么可能在某些浏览器版本中我们无法通过 get_current_user_id() 获取 ID 为此我们可以在 ajax 以上使用 xhrFields 那么它会工作正常。如果是浏览器版本问题。
jQuery.ajax({
type: "POST",
xhrFields: {
withCredentials: true
},
cache: false,
get_current_user_id()
为以下代码返回 0。我确实尝试了一些可用于堆栈溢出的解决方案,但不知何故对我不起作用。我期待解释为什么它返回零以及如何修复?
P.S:我从外部 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;
?>
这可能是直接在外部文件中包含 wp-blog-header.php
的结果。来自 the Codex on get_current_user_id()
:
The user's ID, if there is a current user; otherwise 0.
我不确定您要做什么,但正确的方法是将此逻辑添加到正确的 [=14] 下的 functions.php =].通过执行这两件事之一,您将可以访问经过身份验证的用户。
你必须调用wordpress的用户认证过程。尝试在 get_current_user_id();
之前添加以下代码,如果它不能解决您的问题,它至少会为您指明正确的方向:
$user_id = apply_filters( 'determine_current_user', false );
wp_set_current_user( $user_id );
希望对您有所帮助!
如果您使用的是 ajax 那么可能在某些浏览器版本中我们无法通过 get_current_user_id() 获取 ID 为此我们可以在 ajax 以上使用 xhrFields 那么它会工作正常。如果是浏览器版本问题。
jQuery.ajax({
type: "POST",
xhrFields: {
withCredentials: true
},
cache: false,