Modify the WordPress main query with pre_get_posts: 5 common patterns
WordPress builds and runs the main query (the one behind the Loop on the home page, archives and search) before the template is loaded. When archive.php starts, the posts are already fetched. The pre_get_posts action fires after the query object is created but before the SQL runs, so it is the place to change the number of posts, the post types, the order or the filters, without a second WP_Query in the template. I already wrote about changing the arguments of the global query; here are the patterns I use most often.
Problem: Change how WordPress queries posts on the home page, archives or search (more posts per page, a filter by a custom field, an excluded category) without replacing the main query.
Solution: Hook into pre_get_posts, make sure it is the main query on the front end, and change the parameters with $query->set().
The guard
Always start with these two checks. Without them the changes also hit the admin post lists, widgets, menus and every other query on the page:
<?php
add_action( 'pre_get_posts', 'modify_main_query' );
function modify_main_query( $query ) {
if ( is_admin() || ! $query->is_main_query() ) {
return;
}
// patterns below
}
Inside the callback use the methods of $query ($query->is_home(), $query->is_tag()) rather than the global conditional tags: the global ones describe the main query, which is not always the one being built.
1. Posts per page on archives
<?php
if ( $query->is_archive() || $query->is_home() ) {
$query->set( 'posts_per_page', 12 );
}
Changing it here, not in a custom query in the template, keeps the pagination correct: /page/2/ is calculated with the same number.
2. Exclude a category from the blog page
<?php
if ( $query->is_home() ) {
$news = get_category_by_slug( 'news' );
if ( $news ) {
$query->set( 'category__not_in', array( $news->term_id ) );
}
}
3. Custom post types on tag pages
<?php
if ( $query->is_tag() ) {
$query->set( 'post_type', array( 'post', 'portfolio', 'resource' ) );
}
4. Order a post type archive by a custom field
<?php
if ( $query->is_post_type_archive( 'event' ) ) {
$query->set( 'meta_key', 'event_date' ); // ACF date field, stored as Ymd
$query->set( 'orderby', 'meta_value_num' );
$query->set( 'order', 'ASC' );
}
5. Search only in posts
<?php
if ( $query->is_search() ) {
$query->set( 'post_type', 'post' );
}
By default the search returns pages and all public post types too.
NOTE: The callback changes the query object directly, so it does not return anything. And it has to run before the query: calling $query->set() on the global $wp_query in a template changes nothing, because the posts have already been fetched.