posts_pre_query
云策文档标注
概述
posts_pre_query 是一个 WordPress 过滤器,用于在查询执行前拦截并修改 posts 数组。开发者可以通过此 Hook 返回自定义数据来绕过默认的数据库查询。
关键要点
- 过滤器在 WP_Query 执行数据库查询前触发,允许返回非 null 值以短路 WordPress 的默认查询流程。
- 建议需要分页信息的过滤函数设置 WP_Query 对象的 found_posts 和 max_num_pages 属性,因为这些值在未执行数据库查询时无法自动生成。
- 参数包括 $posts(可返回 WP_Post[]、int[] 或 null)和 $query(WP_Query 实例的引用)。
代码示例
$this->posts = apply_filters_ref_array( 'posts_pre_query', array( null, &$this ) );注意事项
- 此过滤器从 WordPress 4.6.0 版本开始引入。
- 相关函数包括 WP_Query::get_posts(),用于基于查询变量检索 posts 数组。
原文内容
Filters the posts array before the query takes place.
Description
Return a non-null value to bypass WordPress’ default post queries.
Filtering functions that require pagination information are encouraged to set the found_posts and max_num_pages properties of the WP_Query object, passed to the filter by reference. If WP_Query does not perform a database query, it will not have enough information to generate these values itself.
Parameters
Source
$this->posts = apply_filters_ref_array( 'posts_pre_query', array( null, &$this ) );
Changelog
| Version | Description |
|---|---|
| 4.6.0 | Introduced. |