【问题标题】:wordpress wp_get_current_user data not displaying in jason-apiwordpress wp_get_current_user 数据未在 json-api 中显示
【发布时间】:2019-02-06 13:22:49
【问题描述】:

我想在另一个网站上显示一个 WordPress 登录用户 ID 和电子邮件,所以我正在使用 wordpressjson-api 插件创建一个 api,但它不起作用。
当我点击直接链接时,它将数据显示为:

"{\"id\":1,\"email\":\"admin@admin.com\"}" 

但是当我使用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


    【解决方案1】:

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

    WP rest api 提供 cookie 验证方法,但也有插件,您可以在此处阅读更多操作方法:

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

    【讨论】:

      【解决方案2】:

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

      1. 安装JWT Authentication for WP REST API插件进行rest-API认证(阅读插件描述)
      2. 将从插件收到的登录令牌传递给 您创建为标头的路线:授权

      3. 像这样为您创建自定义 Rest-API 路由:

        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;     }
        
      4. 编写自己的函数作为 rest-api 路由上的回调函数 :rest_api_custom_func

      5. 您可以使用自定义回调函数为所欲为

      注意:不需要任何其他插件,使用内置的Wordpress Rest API

      【讨论】:

      • 它不适用于发送登录用户信息。
      • 你完成了这个过程的所有步骤吗?
      • 您能否解释一下“将您从插件收到的登录令牌传递给此路由作为 Header: Authorization”这一点
      • gaurav.rawat12 是我的Skype
      • 我加了你,你有空给我按摩一下
      【解决方案3】:

      我要指出一些可能被忽略的东西。

      您的初始值被转义... "{\"id\":1,\"email\":\"admin@admin.com\"}" 并且在外面有引号。这不是一个正确的 json 字符串。

      应该是:{"id":1,"email":"admin@admin.com"}

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-07-22
        • 2011-09-01
        • 1970-01-01
        • 2019-08-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多