钩子文档

request

💡 云策文档标注

概述

request 过滤器用于修改传递给 WordPress 主 SQL 查询的解析后查询变量数组。它允许开发者在查询执行前调整查询参数,影响页面内容生成,是替代 query_posts() 的一种高效方式。

关键要点

  • request 过滤器应用于主查询执行前,可修改查询变量以改变返回的帖子或页面列表。
  • 建议在 functions.php 中使用此过滤器,避免在模板文件中使用,因为主查询可能已执行。
  • 此过滤器影响所有默认查询,包括管理后台,使用时需谨慎测试以避免破坏网站其他部分。
  • 优势在于减少数据库调用,通过修改 SQL 查询而非执行额外查询来优化性能。

代码示例

add_filter( 'request', 'alter_the_query' );

function alter_the_query( $request ) {
    $dummy_query = new WP_Query();  // 如果不传递查询变量,查询不会运行
    $dummy_query->parse_query( $request );

    // 这是实际的操作;根据需要修改查询变量
    if ( $dummy_query->is_home() )
        $request['category_name'] = 'news';

    return $request;
}

注意事项

  • 不要在模板 PHP 页面中使用此过滤器,因为主查询可能已执行,导致无效。
  • 修改查询变量时,需确保不影响其他查询,特别是管理后台功能。

📄 原文内容

Filters the array of parsed query variables.

Parameters

$query_varsarray
The array of requested query variables.

More Information

  • This filter is applied to the query variables that are passed to the default main SQL query that drives your page’s content. It is applied after additional private query variables have been added in, and is one of the places you can hook into to modify the query that will generate your list of posts (or pages) before the main query is executed and the database is actually accessed.
  • Use this hook within functions.php as an alternative way to alter the posts returned in your Main Loop (as an alternate to query_posts() ). The advantage of using this filter is that it alters the SQL query before it is executed, reducing the number of database calls.
  • While it probably goes without saying, attempts to use this hook from within a template php page will not do anything, as the main query will have already executed at that point.
  • As Rarst mentions, this filter affects all default queries, including calls to the admin Dashboard. You must be extremely careful and test thoroughly to ensure that no other parts of the site break when you modify the query string.

Source

$this->query_vars = apply_filters( 'request', $this->query_vars );

Changelog

Version Description
2.1.0 Introduced.

User Contributed Notes

  1. Skip to note 2 content

    Example migrated from Codex:

    Example usage by scribu (reproduced with permission from wordpress.stackexchange.com):

    add_filter( 'request', 'alter_the_query' );
    
    function alter_the_query( $request ) {
        $dummy_query = new WP_Query();  // the query isn't run if we don't pass any query vars
        $dummy_query->parse_query( $request );
    
        // this is the actual manipulation; do whatever you need here
        if ( $dummy_query->is_home() )
            $request['category_name'] = 'news';
    
        return $request;
    }