How to use current_user_can() in register_rest_route()?

Question

I’m trying to assert current_user_can() in the permission_callback method of a register_rest_route function. However, it always returns false.

Upon further debugging, I see that wp_get_current_user() function returns ID zero, which probably means the $current_user global isn’t available at the moment of execution.

That means this example from the documentation shouldn’t work:

<?php
add_action( 'rest_api_init', function () {
    register_rest_route( 'myplugin/v1', '/author/(?P<id>d+)', array(
        'methods' => 'GET',
        'callback' => 'my_awesome_func',
        'args' => array(
            'id' => array(
                'validate_callback' => 'is_numeric'
            ),
        ),
        'permission_callback' => function () {
            return current_user_can( 'edit_others_posts' );
        }
    ) );
} );

And indeed it doesn’t.

Further debugging:

<?php
// muplugins/test.php
add_action('rest_api_init', function() {

    // Works. Returns current WP_User.
    wp_get_current_user();

    // Works. Returns current WP_User.
    global $current_user;

    register_rest_route('test', 'user', [
       'methods' => 'GET',

        // In a closure. Does not work. Returns zero.
       'callback' => function() {
           var_dump(wp_get_current_user());exit;
       },

        // In a class. Does not work. Returns zero.
        'callback' => [new Something, 'test_wp_get_current_user_in_a_class'], 

        // In a function. Does not work. Returns zero.
        'callback' => 'test_wp_get_current_user',

        'permission_callback' => function() {
            // Does not work. Returns zero.
            wp_get_current_user();

            // Does not work. Returns zero.
            global $current_user;
            $current_user->ID;
        }
    ]);
});

function test_wp_get_current_user()
{
    var_dump(wp_get_current_user());exit;
}

class Something
{
    public function test_wp_get_current_user_in_a_class()
    {
        var_dump(wp_get_current_user());exit;
    }
}

How can I use current_user_can() inside register_rest_route()? Or yet, should I?

0
Lucas Bustamante 3 years 2020-03-26T08:50:59-05:00 0 Answers 119 views 0

Leave an answer

Browse
Browse