How to show a different number of posts for a WordPress category

October 8, 2010 at 9:59 am

WordPress allows you to vary how many blog posts you show on your blog, but it’s a single setting, and affects how many blog posts show over the whole website. This tip allows you to have a different number of posts for a particular category.

I used this tip on a category that’s very image intensive to show only 5 posts rather than 10 posts per page. This allowed me to reduce page load times on this category page, whilst still leaving the rest of the website easy to browse.

Open up archive.php and add the following code before the loop.

        
<?php                
            // If showing just 5 gadgets per page                
            if (is_category('Gadget Gallery')) {
            
                // Get the query URL used to show posts from a certain category
                // based on the URL used by the user.
                global $query_string;

                // Show only 5 posts per page (rather than 10 by default) for anything
                // in this category, but respect all pagination and category selection.
                query_posts($query_string . '&posts_per_page=5');
            }
        ?>

<?
// Example loop (no need to copy and paste this)
if ( have_posts() ) : while ( have_posts() ) : the_post();
 ..
endwhile; else:
 ..
endif;
?>

And then after the loop, just paste this:

<?php
	// Reset Query so rest of website doesn't break.
	if (is_category('Gadget Gallery')) {
		wp_reset_query(); 
	}
?>

You can use any of the conditional tags to determine when to show more or less pages, I chose to use the function that checks for a category by name. I hope it comes in useful!

Thanks to Dan Harrison of WP Doctors for the tip!

Tags: