我想在另一个网站上显示一个登录用户ID和电子邮件的WordPress,所以,我正在使用wordpressjson-api
插件来创建一个api但它不起作用。
当我点击直接链接时,它会将数据显示为:
"{\"id\":1,\"email\":\"[email protected]\"}"
但是当我使用json_decode
并打印数据时,它会显示:
string(22) "{"id":0,"email":false}"
api代码
public function get_loggedin_user_details() {
global $user;
global $wpdb, $json_api;
$current_user = wp_get_current_user();
$myObj->id = $current_user->ID;
$myObj->email = $current_user->user_email;
$logedin_userid = json_encode($myObj);
return $logedin_userid;
}
您没有对您的请求进行身份验证,因此不会记录请求,从而导致ID为0且没有电子邮件。
WP rest api提供了一种cookie身份验证方法,但也有插件,你可以在这里阅读更多关于操作方法:
https://developer.wordpress.org/rest-api/using-the-rest-api/authentication/
我要指出一些可能被忽视的事情。
您的初始值已转义...“{\”id \“:1,\”email \“:\”[email protected] \“}”并在外围引用。这不是一个合适的json字符串。
应该是:{“id”:1,“email”:“[email protected]”}
这是在WP上获取登录用户ID的过程:
注意:不需要任何其他插件,使用内置的add_action( 'rest_api_init', function () {
register_rest_route( 'your_custom_route/v2', '/(?P<slug>[a-zA-Z0-9-]+)', array(
'methods' => 'POST',
'callback' => 'rest_api_custom_func',
) );
} );
function rest_api_custom_func(){
global $user;
global $wpdb;
$current_user = wp_get_current_user();
$myObj->id = $current_user->ID;
$myObj->email = $current_user->user_email;
$logedin_userid = json_encode($myObj);
return $logedin_userid; }