检查请求是否为 API 请求的最佳方法是什么?
请注意,该请求可能是自定义 API 请求,这意味着它可能如下所示:
mysite.com/wp-json/my_namespace/my_version/my_action
Run Code Online (Sandbox Code Playgroud)
很明显,我可以检查API路由wp-json,但应该有一个内置函数来检查。
我需要它来做一些钩子,比如
add_action('init', 'do_something_only_if_api_request');
function do_something_only_if_api_request()
{
if ( ! wp_api_request() ) {
return;
}
// do stuff
}
Run Code Online (Sandbox Code Playgroud)
你可以检查defined('REST_REQUEST')。此常数被定义为true在rest_api_loaded()(否则不定义)。
有一个的WP REST API开发人员讨论关于引进像一个新的功能is_rest_request()。最后他们选择了这个常数。
截至 2016 年 12 月,REST API 文档对于所有看起来不像端点的内容都相当糟糕。
但是,存在一些函数,您可以在文件中找到文档,因为它们有很好的文档记录,请参阅:wordpress/wp-includes/rest-api.php
如果您只想在 REST API 调用上添加操作,那么您可能想要挂钩操作:rest_api_init,它看起来像:
add_action('rest_api_init', 'do_something_only_if_api_request');
function do_something_only_if_api_request($wp_rest_server)
{
// do stuff
}
Run Code Online (Sandbox Code Playgroud)
您可以在 PHPdoc 注释中找到详细信息:
/**
* Fires when preparing to serve an API request.
*
* Endpoint objects should be created and register their hooks on this action rather
* than another action to ensure they're only loaded when needed.
*
* @since 4.4.0
*
* @param WP_REST_Server $wp_rest_server Server object.
*/
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3661 次 |
| 最近记录: |