Modify the global WordPress query on default pages
pre_get_posts fires after the query variable object is created but before the database query runs. It gives you direct access to the $query object for every query WordPress makes, including the main loop, so you can change arguments without duplicating the template or creating a secondary query.
Problem: On default WordPress archive pages like archive.php, how do you change the query arguments that aren’t explicitly set in the template?
Solution: Use the pre_get_posts hook to modify the main query before it runs.
Example: news and events archives
Below, the news archive shows 10 posts per page, and the events archive shows only upcoming events, sorted by start date. The start date is an ACF Date Picker field called start_date; ACF stores it in the database as Ymd, for example 20180410, so dates can be compared as numbers.
add_action( 'pre_get_posts', 'helloadmin_archive_queries' );
function helloadmin_archive_queries( $query ) {
if ( is_admin() || ! $query->is_main_query() ) {
return;
}
if ( $query->is_post_type_archive( 'news' ) ) {
$query->set( 'posts_per_page', 10 );
} elseif ( $query->is_post_type_archive( 'events' ) ) {
// Only events that start today or later.
$query->set( 'posts_per_page', 12 );
$query->set( 'meta_key', 'start_date' );
$query->set( 'orderby', 'meta_value_num' );
$query->set( 'order', 'ASC' );
$query->set( 'meta_query', array(
array(
'key' => 'start_date',
'value' => current_time( 'Ymd' ),
'compare' => '>=',
'type' => 'NUMERIC',
),
) );
}
}
Rules for pre_get_posts
- Always check
$query->is_main_query()and! is_admin(). Without them you also change admin list tables and every secondary query on the page, such as widgets and menus. - Use the
$querymethods ($query->is_post_type_archive(),$query->is_category()) rather than global conditionals likeis_category(): the globals describe the main query, not necessarily the one being filtered. - Do not run a new
WP_Queryorget_posts()inside the callback. It firespre_get_postsagain and adds an extra query on every page load. Filtering in the database withmeta_query, as above, does the same job in one query. current_time( 'Ymd' )uses the site’s time zone from Settings → General, so “today” matches what visitors see.