Number of post for a WordPress archive page

I want to be able to change the amount of post shown on each archive page on a per category basis. Is there something I can change in the loop code or a plugin that gives me that ability?

Thank you SE community.

Related posts

Leave a Reply

3 comments

  1. paste this in your theme function.php file

    add_filter('pre_get_posts', 'Per_category_basis');
    
    function Per_category_basis($query){
        if ($query->is_category) {
            // category named 'books' show 12 posts
            if (is_category('books'){
                $query->set('posts_per_page', 12);
            }
            // category With ID = 32 show only 5 posts
            if (is_category('32'){
                $query->set('posts_per_page', 5);
            }
        }
        return $query;
    
    }
    

    explanation:
    first we check if its actually a category because we don’t want to change anything else.
    if so we check to see and change the number of posts to show, on the first one we check by category name ‘books’ and assign the value of 12 posts_per_page the second one is by category id of ’32’ and we assign the value of 5 posts_per_page just to show you that you can use either one.
    and you can just add as many checks and assignments.

  2. Bainternet’s solution did not work in my case, even though it helped me figure out how to do it correctly.

    The solution is to take the parameter by reference, since else it will just make a copy of the query object.

    add_action('pre_get_posts', 'custom_per_page');
    
    function custom_per_page(&$query) {
    if (is_post_type_archive('custom_post_type_name')) {
        $query->set('posts_per_page', 4);
    }
    return;
    }