Wordpress REST API - 如何创建具有空命名空间的 API 路由?
Wordpress REST API - How do I create an API route with empty namespace?
我有一个带有路由 https://example.com/wp-json/videos. This was created with the JSON rest API plugin 的 API,由于插件停止工作,我需要使用 WP Rest API 重新创建它。
我发现使用 WP rest API,我无法创建具有空命名空间或路由的路由,因此我只能
/videos
在 api 路线中。
我该怎么做?
我试过这段代码
function handle_routes($rest ) {
$video_api = new Video_API;
$routes = $video_api->register_routes();
foreach ($routes as $route => $data) {
$namespace = explode( '/', trim($route, '/'))[0];
$rest->register_route($namespace, $route, [
'methods' => $data[0][1],
'callback' => $data[0][0]
]);
}
}
add_action( 'rest_api_init', 'handle_routes', 10, 1);
所有参数都正确,但出现 rest_no_route 错误,因此未注册路由。
$routes['/videos/(?P<id>\d+)'] = array(
array( array( $this, 'get_video'), WP_JSON_Server::READABLE)
);
这是发送到方法的路由示例之一。
试试这个,这应该可以满足您的要求。
add_action('rest_api_init', function($rest) {
$rest->register_route('videos', '/videos', [
'methods' => 'GET',
'callback' => '' //<--your callback function for videos
]);
});
这里发生的事情是您直接向 WP_REST_Server
对象添加一个新路由,它会创建一个具有空命名空间的路由。
我有一个带有路由 https://example.com/wp-json/videos. This was created with the JSON rest API plugin 的 API,由于插件停止工作,我需要使用 WP Rest API 重新创建它。
我发现使用 WP rest API,我无法创建具有空命名空间或路由的路由,因此我只能
/videos
在 api 路线中。
我该怎么做?
我试过这段代码
function handle_routes($rest ) {
$video_api = new Video_API;
$routes = $video_api->register_routes();
foreach ($routes as $route => $data) {
$namespace = explode( '/', trim($route, '/'))[0];
$rest->register_route($namespace, $route, [
'methods' => $data[0][1],
'callback' => $data[0][0]
]);
}
}
add_action( 'rest_api_init', 'handle_routes', 10, 1);
所有参数都正确,但出现 rest_no_route 错误,因此未注册路由。
$routes['/videos/(?P<id>\d+)'] = array(
array( array( $this, 'get_video'), WP_JSON_Server::READABLE)
);
这是发送到方法的路由示例之一。
试试这个,这应该可以满足您的要求。
add_action('rest_api_init', function($rest) {
$rest->register_route('videos', '/videos', [
'methods' => 'GET',
'callback' => '' //<--your callback function for videos
]);
});
这里发生的事情是您直接向 WP_REST_Server
对象添加一个新路由,它会创建一个具有空命名空间的路由。