Different Number of Posts on Homepage, Category, Post Type

Print Page

This code snippet will allow you to show different number of posts on homepage, per category, and post type without using any plugin.

function different_post_per_page( $query ) {
    if ( $query->is_main_query() && $query->is_home() ) {
        //Display 1 post per page on the homepage
        $query->query_vars['posts_per_page'] = 1;
        return;
    }
     if ($query->is_main_query() && $query->is_category('dinner') ) {
        //Display 5 posts per page for a category called 'dinner'
        $query->query_vars['posts_per_page'] = 5;
        return;
    }
     if ( $query->is_main_query() && $query->is_post_type_archive('receipe') ) {
        //Display 10 posts per page for a custom post type called 'receipe'
        $query->query_vars['posts_per_page'] = 10;
        return;
    }
}
add_action('pre_get_posts', 'different_post_per_page', 1);

Another use of this hook can be to include or exclude posts from certain categories on homepage.