我已经尝试注册路由,尝试了各种不同的参数,觉得我的代码看起来像这个网站上的许多示例,但不明白为什么它不起作用。
//Register REST Route
add_action(\'rest_api_init\', \'add_advent_api\');
function add_advent_api()
{
register_rest_route(\'adventapi/v1\', \'/adventapi/\', array(
\'methods\' => \'WP_REST_Server::READABLE\',
\'callback\' => function () {
return \'hello\';
},
\'args\' => array(
\'adventyear\' => array(
\'required\' => true,
\'type\' => \'integer\',
\'description\' => \'Year required\',
\'minimum\' => 1972,
\'maximum\' => 9999,
),
\'adventday\' => array(
\'required\' => true,
\'type\' => \'integer\',
\'minimum\' => 1,
\'maximum\' => 24,
),
),
\'permission_callback\' => function () {
return true;
}
));
}
function advent_query(WP_REST_Request $request)
{
return \'i work\';
/* $adventyear = $_GET[\'adventyear\'];
$adventday = $_GET[\'adventday\'];
$args = array(
\'post_type\' => \'advent\',
\'meta_query\' => array(
\'relation\' => \'AND\',
array(
\'key\' => \'advent_year\',
\'value\' => $adventyear,
),
array(
\'key\' => \'advent_day\',
\'value\' => $adventday,
),
),
);
$query = new WP_Query($args);
if ($query->have_posts()) {
echo \'i ahve posts\';
} else {
echo \'No Results\';
} */
}
最合适的回答,由SO网友:Sally CJ 整理而成
代码中存在一个问题:HTTP方法无效,因为WP_REST_Server::READABLE
是一个类常量,因此它不应该用引号括起来:
register_rest_route( \'adventapi/v1\', \'/adventapi/\', array(
// \'methods\' => \'WP_REST_Server::READABLE\', // wrong
// \'methods\' => "WP_REST_Server::READABLE", // wrong
\'methods\' => WP_REST_Server::READABLE, // correct
// ... other args.
) );
您还应该确保使用正确的请求/HTTP方法以及正确的端点URL,例如:。
https://example.com/wp-json/adventapi/v1/adventapi
, 向API发出请求时。