WordPress: Exclude category from home page breaks post navigation

Here at Kino Creative we use Wordpress a lot as a cost effective (ie. free!) content management system (CMS) . Wordpress is very flexible if you are prepared to get your hands dirty with the template code but being open source the quality of documentation can be a little patchy.

Here at Kino Creative we use WordPress a lot as a cost effective (ie. free!) content management system (CMS). WordPress is very flexible if you are prepared to get your hands dirty with the template code but being open source the quality of documentation can be a little patchy.

One of the most common queries is how to exclude posts from certain categories from appearing on the homepage. It is actually very easy when you know how. Your homepage template (index.php) will include what is known as “the loop”, and this is the part that pulls in the content from the database. It should look something like this:

<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); ?>
//Stuff that displays the posts
<?php endwhile; ?>
<?php else : ?>
//Stuff to show if no posts were found
<?php endif; ?>

To exclude categories you need to add a query before all that to tell WordPress what to exclude:

<?php
if (is_home()) {
query_posts("cat=-1,-2,-3");
}
?>

The above example taken from the WordPress Codex will return all posts except those in categories with the id 1, 2 and 3. The easiest way to find out your category id’s is to install the “Reveal IDs for WP Admin” plugin.

What the WordPress Codex and virtually all of the tutorials I have seen don’t tell you is that this will break the post navigation. By post navigation I mean the older/newer post links that show if you have more posts than the number set to be displayed per page in the WordPress dashboard. With these navigation links broken, clicking them will simply display the same page rather than showing the older or newer posts.

To fix the post navigation you should amend the above code to this:

<?php
if (is_home()) {
$page = (get_query_var('paged')) ? get_query_var('paged') : 1;
query_posts("paged=$page&cat=-1,-2,-3");
}
?>

This addition lets WordPress know that this page is should be paginated so it will enable the older posts/newer posts links correctly.