WP_GET_CURRENT_USER()函数在REST API回调函数中不工作

时间:2018-04-04 作者:Shah Alom

考虑以下类别。

<?php
class MCQAcademy_Endpoint extends WP_REST_Controller {

    /**
     * Register the routes for the objects of the controller.
     */
    public function register_routes() {
        $version = \'1\';
        $namespace = \'custompath/v\' . $version;
        $base = \'endpointbase\';

        register_rest_route(
            $namespace,
            \'/\' . $base,
            array(
                array(
                    \'methods\'         => WP_REST_Server::READABLE,
                    \'callback\'        => array( $this, \'get_items\' ),
                    \'permission_callback\' => array( $this, \'get_items_permissions_check\' ),
                    \'args\'            => array(),
                )
            )
        );
    }

    /**
     *
     */
    public function get_items( $request ) {
        $rs = array(
            \'data\' => array(),
            \'request\' => array(
                \'lang\' => \'en\',
            ),
        );

        $args = array();
        $items = get_posts( $args );

        foreach( $items as $item ) {
            $itemdata = $this->prepare_item_for_response( $item, $request );
            $rs[\'data\'][] = $this->prepare_response_for_collection( $itemdata );
        }

        $rs[\'wp_get_current_user\'] = wp_get_current_user(); // Does not output as expected

        return new WP_REST_Response( $rs, 200 );
    }

    /**
     * Check if a given request has access to get items
     */
    public function get_items_permissions_check( $request ) {
        return true; // to make readable by all
    }


    /**
     * Prepare the item for create or update operation
     */
    protected function prepare_item_for_database( $request ) {
        return $request;
    }

    /**
     * Prepare the item for the REST response
     */
    public function prepare_item_for_response( $item, $request ) {
        $data = array(
            \'ID\' => $item->ID,
            \'post_content\' => wpautop($item->post_content),
            \'post_title\' => $item->post_title,
        );

        return $data;
    }

    /**
     * Get the query params for collections
     */
    public function get_collection_params() {
        return array(
            \'page\'     => array(
                \'description\'        => \'Current page of the collection.\',
                \'type\'               => \'integer\',
                \'default\'            => 1,
                \'sanitize_callback\'  => \'absint\',
            ),
            \'per_page\' => array(
                \'description\'        => \'Maximum number of items to be returned in result set.\',
                \'type\'               => \'integer\',
                \'default\'            => 10,
                \'sanitize_callback\'  => \'absint\',
            ),
            \'search\'   => array(
                \'description\'        => \'Limit results to those matching a string.\',
                \'type\'               => \'string\',
                \'sanitize_callback\'  => \'sanitize_text_field\',
            ),
        );
    }

    // Register our REST Server
    public function hook_rest_server(){
        add_action( \'rest_api_init\', array( $this, \'register_routes\' ) );
    }
}

$myEndpoint = new MCQAcademy_Endpoint();
$myEndpoint->hook_rest_server();
除了打电话给wp_get_current_user() 中的函数get_items() 函数返回空用户,即使用户是logged in 在网站上。

4 个回复
SO网友:Pabamato

登录到您的网站并不意味着用户在REST API请求中经过身份验证,这就是为什么您没有获得正确的用户或Id = 0

请查看文档上的REST API验证方法:
https://developer.wordpress.org/rest-api/using-the-rest-api/authentication/

对于手动发出Ajax请求的开发人员,每个请求都需要传递nonce。API使用nonces并将操作设置为wp\\u rest。然后,可以通过wpnance数据参数(POST data或GET请求的查询中)或通过X-WP-Nonce头将这些数据传递给API。如果未提供nonce,API会将当前用户设置为0,将请求转换为未经验证的请求,即使您登录到WordPress。

对于远程身份验证,我建议使用JWT插件快速启动:

或者您可以使用文档中建议的选项:

SO网友:John Dee

如果传入的API调用没有nonce集,WordPress将取消对请求的身份验证,杀死当前用户并使请求未经身份验证。这种CSFR保护是自动的,除了包含nonce之外,您无需为其工作做任何事情。

解决此问题的方法是包含nonce。类似这样:

$_wpnonce = wp_create_nonce( \'wp_rest\' );
echo "<input type = \'hidden\' name = \'_wpnonce\' value = \'$_wpnonce\' />";
并将其包含在API请求中。nonce必须被称为“\\u wpnance”,操作必须是“wp\\u rest”,API才能工作。它可以放在URL或帖子正文中。

SO网友:leymannx

为了获得一个完整的代码示例,这里提供了一个示例插件,介绍如何通过REST检索当前用户的ID。

my-plugin.php

class MyPlugin {

  public function __construct() {

    add_action(\'wp_enqueue_scripts\', [$this, \'scripts\']);
    add_action(\'rest_api_init\', [$this, \'rest\']);
  }

  function scripts() {

    // Add JS.
    wp_enqueue_script(\'my-plugin\', plugin_dir_url(__FILE__) . \'js/scripts.js\', [\'jquery\'], NULL, TRUE);
    // Pass nonce to JS.
    wp_localize_script(\'my-plugin\', \'MyPluginSettings\', [
      \'nonce\' => wp_create_nonce(\'wp_rest\'),
    ]);
  }

  function rest() {

    // Register route.
    register_rest_route(\'my-plugin/v1\', \'/uid\', [
      \'methods\'  => WP_REST_Server::READABLE,
      \'callback\' => [$this, \'rest_callback\'],
    ]);
  }

  function rest_callback($data) {

    // Get current user ID.
    $data = [
      \'uid\' => get_current_user_id(),
    ];

    $response = new WP_REST_Response($data, 200);
    // Set headers.
    $response->set_headers([\'Cache-Control\' => \'must-revalidate, no-cache, no-store, private\']);

    return $response;
  }

}

new MyPlugin();

js/scripts.js

(function($) {

  $(document).ready(function() {

    var settings = MyPluginSettings;

    $.ajax({
      url: \'/wp-json/my-plugin/v1/uid\',
      method: \'GET\',
      beforeSend: function(xhr) {
        xhr.setRequestHeader(\'X-WP-Nonce\', settings.nonce);
      }
    }).done(function(response) {

      // Will return your UID.
      console.log(response);
    });

  });

})(jQuery);
资源:https://developer.wordpress.org/rest-api/using-the-rest-api/authentication/

SO网友:user3308965

wp_get_current_user() 无法工作,因为您的用户设置不完美。请参见中的以下代码/wp-includes/user.php 供参考。

if ( ! empty( $current_user ) ) {
    if ( $current_user instanceof WP_User ) {
        return $current_user;
    }

    // Upgrade stdClass to WP_User
    if ( is_object( $current_user ) && isset( $current_user->ID ) ) {
        $cur_id       = $current_user->ID;
        $current_user = null;
        wp_set_current_user( $cur_id );
        return $current_user;
    }

    // $current_user has a junk value. Force to WP_User with ID 0.
    $current_user = null;
    wp_set_current_user( 0 );
    return $current_user;
}

if ( defined( \'XMLRPC_REQUEST\' ) && XMLRPC_REQUEST ) {
    wp_set_current_user( 0 );
    return $current_user;
}
您所需要做的就是在API开始时wp\\u set\\u current\\u user({user\\u id})。

结束

相关推荐

Php致命错误:无法将WP_REST_RESPONSE类型的对象用作wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php中

我向WordPress添加了一个自定义端点,如下所示: add_action( \'rest_api_init\', function () { register_rest_route( \'menc/v1\', \'/crosscat/(?P[\\w-]+)/(?P[\\w-]+)\', array( \'methods\' => \'GET\', \'callback\' => \'dept_cat_api\',&#x