This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.
Change posts_per_page on post type archives, search results and other WordPress pages
Modify the posts_per_page parameter according to the current post type or page being viewed
WordPress allows you to set a site-wide posts_per_page value using its ‘Blog pages show at most’ value under the Reading page of Settings. However, if you’re working with WordPress’ custom post types, you may wish to change the number of posts displayed according to the post type archive being viewed.
The code snippet below will allow you to modify the main WordPress Query’s posts_per_page
parameter according to the current post type being displayed.
Since we only want this code to affect the main WP Query on each page and we don’t want it to run in the admin area of WordPress, we first make those checks using is_admin()
and is_main_query()
. Following this, we can set a custom posts_per_page
parameter on post type archives using is_post_type_archive()
.
Using the same logic, we can also amend the posts_per_page
parameter for search result pages by using the is_search()
conditional tag. Further conditionals such as is_home()
can be used to targeted specific WordPress pages.
/**
* Change posts per page by post type
*/
function bb_change_posts_per_page( $query ) {
if ( is_admin() || ! $query->is_main_query() ) {
return;
}
if ( is_post_type_archive( 'team' ) ) {
$query->set( 'posts_per_page', 12 );
}
if ( is_post_type_archive( 'work' ) ) {
$query->set( 'posts_per_page', -1 );
}
if ( is_search() ) {
$query->set( 'posts_per_page', 12 );
}
}
add_filter( 'pre_get_posts', 'bb_change_posts_per_page' );