The pre_get_posts
hook can be used to modify queries before they’re run. You can use $query->set()
to set arguments on the WP_Query
object, and $query->is_main_query()
in the callback to limit your changes to the main query:
add_action(
'pre_get_posts',
function( $query ) {
if ( ! is_admin() && $query->is_main_query() ) {
$query->set( 'posts_per_page', 12 );
}
}
);
You can’t target specific templates, but if you want the change to only affect archives, you can use $query->is_archive()
, which will be true for date, taxonomy and post type archives, or if you only want to apply the changes to the category archives, you can use $query->is_category()
. Many of the normal conditional functions are available as methods for checking the current query.