在哪里注册 REST 路由到 wordpress 插件端点
Where to register REST route to wordpress plugin endpoint
注册功能该去哪里? (register_rest_route()
)
- 一定要在theme/childfunctions.php吗?
- 或者它可以在插件基础 php 文件中吗? (例如 \wp-content\plugins\example\example.php)
是否有任何文档可以阐明这一点?
官方文档中没有提到:
https://developer.wordpress.org/rest-api/extending-the-rest-api/routes-and-endpoints/
同样,端点函数必须存储在哪里?注册函数只是命名,没有指定路径
例如,你可以这样做吗:
- 注册函数调用(
register_rest_route
)进入主插件文件(例如\wp-content\plugins\example\example。php)
- 端点函数在其他一些插件文件中(例如 \wp-content\plugins\example\sub-path-stuff\example-controller.php)
如果是,怎么做?
以下 link 似乎尝试这样做但未指定这些属性(例如 \wp-content\plugins\example\example.php)
所以 register_rest_route 进入“rest_api_init”动作挂钩,路由的回调可以在同一个文件或外部文件中定义(然后你可以在主文件中要求它,这样你就可以添加他们 route/s)。这是一个例子:
假设您有一个插件“api-test”,它位于:\wp-content\plugins\api-test 我们将添加 api-test.php 作为主插件文件(将为了这个例子,是功能性的而不是 oop)。在 api-test.php 里面你可以有这样的东西:
/**
* @wordpress-plugin
* Plugin Name: WP Rest api testing..
*/
/**
* at_rest_testing_endpoint
* @return WP_REST_Response
*/
function at_rest_testing_endpoint()
{
return new WP_REST_Response('Howdy!!');
}
/**
* at_rest_init
*/
function at_rest_init()
{
// route url: domain.com/wp-json/$namespace/$route
$namespace = 'api-test/v1';
$route = 'testing';
register_rest_route($namespace, $route, array(
'methods' => WP_REST_Server::READABLE,
'callback' => 'at_rest_testing_endpoint'
));
}
add_action('rest_api_init', 'at_rest_init');
这是一个非常简单的示例,所有内容都在同一个文件中。
注册功能该去哪里? (register_rest_route()
)
- 一定要在theme/childfunctions.php吗?
- 或者它可以在插件基础 php 文件中吗? (例如 \wp-content\plugins\example\example.php)
是否有任何文档可以阐明这一点?
官方文档中没有提到: https://developer.wordpress.org/rest-api/extending-the-rest-api/routes-and-endpoints/
同样,端点函数必须存储在哪里?注册函数只是命名,没有指定路径
例如,你可以这样做吗:
- 注册函数调用(
register_rest_route
)进入主插件文件(例如\wp-content\plugins\example\example。php) - 端点函数在其他一些插件文件中(例如 \wp-content\plugins\example\sub-path-stuff\example-controller.php)
如果是,怎么做?
以下 link 似乎尝试这样做但未指定这些属性(例如 \wp-content\plugins\example\example.php)
所以 register_rest_route 进入“rest_api_init”动作挂钩,路由的回调可以在同一个文件或外部文件中定义(然后你可以在主文件中要求它,这样你就可以添加他们 route/s)。这是一个例子:
假设您有一个插件“api-test”,它位于:\wp-content\plugins\api-test 我们将添加 api-test.php 作为主插件文件(将为了这个例子,是功能性的而不是 oop)。在 api-test.php 里面你可以有这样的东西:
/**
* @wordpress-plugin
* Plugin Name: WP Rest api testing..
*/
/**
* at_rest_testing_endpoint
* @return WP_REST_Response
*/
function at_rest_testing_endpoint()
{
return new WP_REST_Response('Howdy!!');
}
/**
* at_rest_init
*/
function at_rest_init()
{
// route url: domain.com/wp-json/$namespace/$route
$namespace = 'api-test/v1';
$route = 'testing';
register_rest_route($namespace, $route, array(
'methods' => WP_REST_Server::READABLE,
'callback' => 'at_rest_testing_endpoint'
));
}
add_action('rest_api_init', 'at_rest_init');
这是一个非常简单的示例,所有内容都在同一个文件中。