wordpress wp_get_current_user数据不在json-api中显示

问题描述 投票:3回答:3

我想在另一个网站上显示一个登录用户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;
  }
php wordpress wordpress-json-api
3个回答
0
投票

您没有对您的请求进行身份验证,因此不会记录请求,从而导致ID为0且没有电子邮件。

WP rest api提供了一种cookie身份验证方法,但也有插件,你可以在这里阅读更多关于操作方法:

https://developer.wordpress.org/rest-api/using-the-rest-api/authentication/


0
投票

我要指出一些可能被忽视的事情。

您的初始值已转义...“{\”id \“:1,\”email \“:\”[email protected] \“}”并在外围引用。这不是一个合适的json字符串。

应该是:{“id”:1,“email”:“[email protected]”}


0
投票

这是在WP上获取登录用户ID的过程:

  1. 安装JWT Authentication for WP REST API插件进行rest-API认证(阅读插件描述)enter image description here
  2. 将您从插件收到的登录令牌传递给您创建为Header:Authorization enter image description here的路由
  3. 像这样创建自定义Rest-API Route: qazxsw poi
  4. 在rest-api路由上编写自己的函数作为回调函数:rest_api_custom_func
  5. 您可以使用自定义回调函数执行任何操作

注意:不需要任何其他插件,使用内置的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; }

© www.soinside.com 2019 - 2024. All rights reserved.