Attention Interested in functions, hooks, classes, or methods? Check out the new WordPress Code Reference!

Plugin API/Filter Reference/request

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.

Here's an example usage by scribu (reproduced with permission from wordpress.stackexchange.com):

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;
add_filter( 'request', 'alter_the_query' );

Usage Note

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.


For more in-depth discussion of how WordPress generates and handles its queries, review these articles: Query Overview and Custom Queries


Also, see the 'parse_query' and 'pre_get_posts'