The ‘query’ filter allows you to modify the database query in WordPress before it is executed.
This can be useful for customizing the behavior of queries to meet specific needs. Keep in mind that some queries occur before plugins are loaded, so this filter may not apply to all cases.
Usage
To use the apply_filters( 'query', string $query )
filter, create a custom function and then attach it to the filter using the add_filter()
function. Here’s a basic code example:
function custom_query_filter( $query ) { // Modify the $query here return $query; } add_filter( 'query', 'custom_query_filter' );
Parameters
$query (string)
: The database query that you want to modify.
Examples
Exclude a specific category from the main query
function exclude_category_from_query( $query ) { if ( is_home() && !is_admin() ) { $query .= " AND term_taxonomy_id != 3"; } return $query; } add_filter( 'query', 'exclude_category_from_query' );
In this example, we create a function exclude_category_from_query()
that checks if the current page is the home page and not the admin dashboard. If so, it modifies the $query
to exclude posts from the category with the ID of 3.
Limit the number of search results
function limit_search_results( $query ) { if ( is_search() ) { $query .= " LIMIT 5"; } return $query; } add_filter( 'query', 'limit_search_results' );
The limit_search_results() function modifies the $query
to limit the number of search results displayed to 5 when the user performs a search.
Order posts by title
function order_posts_by_title( $query ) { if ( is_home() && !is_admin() ) { $query .= " ORDER BY post_title ASC"; } return $query; } add_filter( 'query', 'order_posts_by_title' );
In this example, the order_posts_by_title()
function modifies the $query
to display posts ordered by their title in ascending order on the home page.
Hide posts older than 30 days
function hide_old_posts( $query ) { if ( is_home() && !is_admin() ) { $query .= " AND post_date >= NOW() - INTERVAL 30 DAY"; } return $query; } add_filter( 'query', 'hide_old_posts' );
The hide_old_posts() function modifies the $query
to display only posts that are less than 30 days old on the home page.
Display posts from a specific author
function display_author_posts( $query ) { if ( is_home() && !is_admin() ) { $author_id = 1; $query .= " AND post_author = $author_id"; } return $query; } add_filter( 'query', 'display_author_posts' );
In this example, the display_author_posts()
function modifies the $query
to display only posts written by the author with the ID of 1 on the home page.