Show different number of Posts Per Page for different Post Types

During work for a recent client, I needed to limit the number of posts on one archive, yet show every post on a single page for another. By default WordPress uses the value set in the admin screen ‘Settings’ > ‘Reading’ and seen as ‘Blog pages show at most’.

But in my case, I needed this limit for the normal Post type, but the trouble was I didn’t want these values carried into either of the 2 Custom Post Types I was using and needed 2 additional values. Here’s how I set this up using a function in your themes functions.php or a standalone plugin:

function custom_posts_per_page($query) {
    if ( is_post_type_archive('custom_post_type_1') ) {
        $query->set('posts_per_page', -1); // this post type archive now shows every post on a single page
        $query->set( 'order', 'ASC' );
        $query->set( 'orderby', 'title' );
    } //endif
    if ( is_post_type_archive('custom_post_type_2') ) {
        $query->set('posts_per_page', 16); // this post type archive shows 16 per page
        $query->set( 'order', 'ASC' );
        $query->set( 'orderby', 'title' );
    } //endif
//this adds the function above to the 'pre_get_posts' action
add_action('pre_get_posts', 'custom_posts_per_page');

In the above, add your own post type names in place of ‘custom_post_type_1’ and ‘custom_post_type_2’.

Useful post? Share it

Leave a Reply

Your email address will not be published. Required fields are marked *