wp_get_current_user() function not working in Rest API callback function

Consider the following class.

<?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,
            "https://wordpress.stackexchange.com/" . $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();

Everything is going well except calling the wp_get_current_user() function in the get_items() function return empty user even though the user is logged in in the website.

4

Logged in on your website doesn’t mean the user is authenticated in the REST API request, that’s why you are not getting the correct user or a Id = 0

Please take a look to the REST API authentication methods on the docs:
https://developer.wordpress.org/rest-api/using-the-rest-api/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.

For remote authentication I’d recommend the JWT plugin for a quick start:

  • https://wordpress.org/plugins/jwt-authentication-for-wp-rest-api/

Or you can use the ones suggested on the docs:

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

Leave a Comment