英文:
WordPress wp_get_current_user() returns empty payload while a user is logged-in
问题
In WordPress 6.2.2,我正在尝试定义一个REST API监听器,该监听器将返回当前已登录的用户。
我将以下代码添加到我的functions.php文件(我的子主题)中,它正在响应另一个浏览器标签中的请求。但是,尽管在另一个标签中我有一个有效的用户(管理员)已登录,但我得到了以下结果。
结果始终是:
{
"data": {},
"ID": 0,
"caps": [],
"cap_key": null,
"roles": [],
"allcaps": [],
"filter": null
}
functions.php中的代码:
add_action('rest_api_init', function () {
register_rest_route('mytheme/v1', '/current-user', array(
'methods' => 'GET',
'callback' => 'get_current_user1',
'permission_callback' => function () {
return true;
}
));
});
function get_current_user1($request) {
$user = wp_get_current_user();
return $user;
}
另一个浏览器标签中显示的已登录用户:
我尝试过在两个不同的WordPress站点上,结果始终相同。我漏掉了什么?
英文:
In WordPress 6.2.2, I'm trying to define a rest api listener that will return the currently logged-in user.
I added the following code to my functions.php file (of my child theme) and it is responding to my requests in another browser tab.
However, I am getting the following result, even though in another tab I have a valid user (admin) logged-in.
Result is always:
{
"data": {},
"ID": 0,
"caps": [],
"cap_key": null,
"roles": [],
"allcaps": [],
"filter": null
}
Code in functions.php:
add_action('rest_api_init', function () {
register_rest_route('mytheme/v1', '/current-user', array(
'methods' => 'GET',
'callback' => 'get_current_user1',
'permission_callback' => function () {
return true;
}
));
});
function get_current_user1($request) {
$user = wp_get_current_user();
return $user;
}
Logged-in user shown in another browser tab:
I tried this with TWO different WordPress sites, same result always.
What am I missing?
答案1
得分: 1
对于进行手动Ajax请求的开发人员,需要在每个请求中传递一次性令牌。API使用带有动作设置为wp_rest的一次性令牌。然后可以通过_wpnonce数据参数(POST数据或GET请求的查询)或通过X-WP-Nonce标头将这些令牌传递给API。如果没有提供令牌,API将当前用户设置为0,将请求转换为未经身份验证的请求,即使您已登录WordPress。
来源:
https://developer.wordpress.org/rest-api/using-the-rest-api/authentication/#cookie-authentication
英文:
> For developers making manual Ajax requests, the nonce will need to be passed with each request. The API uses nonces with the action set to wp_rest. These can then be passed to the API via the _wpnonce data parameter (either POST data or in the query for GET requests), or via the X-WP-Nonce header. If no nonce is provided the API will set the current user to 0, turning the request into an unauthenticated request, even if you’re logged into WordPress.
Source:
https://developer.wordpress.org/rest-api/using-the-rest-api/authentication/#cookie-authentication
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论