钩子文档

posts_request

💡 云策文档标注

概述

posts_request 是一个 WordPress 过滤器,用于在发送 SQL 查询前修改完整的查询字符串。它允许开发者自定义 WP_Query 生成的 SQL 语句。

关键要点

  • 过滤器名称:posts_request
  • 参数:$request(完整的 SQL 查询字符串)和 $query(WP_Query 实例,通过引用传递)
  • 应用场景:在 WP_Query::get_posts() 中调用,用于调整查询逻辑
  • 版本历史:自 WordPress 2.0.0 引入

代码示例

add_filter('posts_request', 'custom_posts_request', 10, 2);
function custom_posts_request($request, $query) {
    // 修改 $request 字符串,例如添加自定义条件
    if ($query->is_search()) {
        $request = str_replace('WHERE 1=1', 'WHERE 1=1 AND custom_field = value', $request);
    }
    return $request;
}

注意事项

  • SQL 查询示例包括 SELECT、JOIN、WHERE 等子句,需谨慎修改以避免语法错误
  • 参数 $query 为引用传递,可直接操作 WP_Query 实例
  • 相关函数:WP_Query::get_posts(),位于 wp-includes/class-wp-query.php

📄 原文内容

Filters the completed SQL query before sending.

Parameters

$requeststring
The complete SQL query.
$queryWP_Query
The WP_Query instance (passed by reference).

More Information

The input of this filter is the post request SQL, something like the following:
<br>SELECT SQL_CALC_FOUND_ROWS wp_posts.* FROM wp_posts LEFT JOIN wp_posts AS p2 ON ( wp_posts.post_parent = p2.ID ) WHERE 1=1 AND wp_posts.ID IN ( 3, 632 ) AND wp_posts.post_type != 'revision' AND ( ( wp_posts.post_status = 'publish' ) OR ( wp_posts.post_status = 'inherit' AND ( p2.post_status = 'publish' ) ) ) ORDER BY wp_posts.post_date DESC LIMIT 0, 20

Source

$this->request = apply_filters_ref_array( 'posts_request', array( $this->request, &$this ) );

Changelog

Version Description
2.0.0 Introduced.