rest_{$this->post_type}_query
云策文档标注
概述
rest_{$this->post_type}_query 是一个动态 Hook,用于在通过 REST API 查询文章时过滤 WP_Query 参数。它允许开发者向文章集合请求添加额外参数或设置默认值。
关键要点
- 这是一个动态 Hook,名称中的 $this->post_type 指代文章类型 slug,例如 rest_post_query、rest_page_query。
- 主要用于在 WP_REST_Posts_Controller::get_items() 中修改 WP_Query 参数,以定制 REST API 查询行为。
- Hook 接受两个参数:$args(WP_Query 参数数组)和 $request(WP_REST_Request 对象)。
- 从 WordPress 5.7.0 开始,此 Hook 在 tax_query 查询参数生成后执行,需注意执行时机变化。
代码示例
function query_book_by_year($args, $request) {
if(isset($request["year"]) && intval($request["year"]) > 1500) {
$args['meta_key'] = 'year';
$args['meta_value'] = intval($request["year"]);
}
return $args;
}
add_filter('rest_book_query', 'query_book_by_year', 10, 2);注意事项
- 使用此 Hook 时,需确保参数修改符合 WP_Query 规范,避免破坏查询逻辑。
- 调试时,可通过在 WP_REST_Posts_Controller::get_items() 方法中设置断点或输出 $posts_query->request 来查看生成的 SQL 语句。
- 注意 Hook 名称的动态性,根据实际文章类型替换 rest_{$this->post_type}_query 中的占位符。
原文内容
Filters WP_Query arguments when querying posts via the REST API.
Description
The dynamic portion of the hook name, $this->post_type, refers to the post type slug.
Possible hook names include:
rest_post_queryrest_page_queryrest_attachment_query
Enables adding extra arguments or setting defaults for a post collection request.
Parameters
$argsarray-
Array of arguments for WP_Query.
$requestWP_REST_Request-
The REST API request.
Source
$args = apply_filters( "rest_{$this->post_type}_query", $args, $request );
Skip to note 3 content
Haris
Code example:
function query_book_by_year($args, $request) { if(isset($request["year"]) && intval($request["year"]) > 1500) { $args['meta_key'] = 'year'; $args['meta_value'] = intval($request["year"]); } return $args; } add_filter('rest_book_query', 'query_book_by_year', 10, 2);Skip to note 4 content
Yan Sern
I wanted to see the SQL generated from the filters I’ve added. However, using
&debug;=sqlon the http request parameter didn’t work for me.You can set a breakpoint at line 299 (at least at the time of writing) under
class-wp-rest-posts-controller.php@get_items()method, which looks like this:$posts_query = new WP_Query(); // line 298 $query_result = $posts_query->query( $query_args ); // line 299Or if you don’t have a debugger setup yet, you can do:
$posts_query = new WP_Query(); $query_result = $posts_query->query( $query_args ); echo $posts_query->request; exit;