我有一个路由为https://example.com/wp-json/videos的API。这是使用JSON rest API plugin创建的,随着插件停止工作,我需要使用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);
但是它给出了一条找不到路由的错误,因此未注册路由
尝试一下,这应该满足您的要求。
add_action('rest_api_init', function($rest) {
$rest->register_route('videos', '/videos', [
'methods' => 'GET',
'callback' => '' //<--your callback function for videos
]);
});
这里发生的事情是您直接向WP_REST_Server
对象添加了一条新路由,并创建了一个带有空名称空间的路由。