我试图断言current_user_can()
在permission_callback
a的方法register_rest_route
作用但是,它总是返回false。
经过进一步调试,我发现wp_get_current_user()
函数返回ID零,这可能意味着$current_user
全局在执行时不可用。
这意味着this example 从文档中可以看出:
<?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\' );
}
) );
} );
事实上,事实并非如此。
进一步调试:
<?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;
}
}
如何使用
current_user_can()
在…内
register_rest_route()
? 或者,我应该吗?