Excluding a category from the front page in WordPress

This is a very well known trick where we use the query_posts() template tag to control which posts to show up. The code has to be placed above the Loop in the index.php template file.

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

The code checks whether we are in home page and if it is, it excludes the category with id 3 from displaying in it. The category id can be found out from the wordpres’s Edit Category pages by mouse hovering the required category and its id will be shown in the browser’s status bar.
More than one category could be excluded by using a code like this, query_posts("cat=-2,-6,-8")

However, i recently noticed that it breaks the pagination, and so the next and previous page links at the bottom only shows the same home page. Pagination is the feature by which we split the home page into pages based on the max number of posts that can be displayed in the page.

The problem was because, the call to query_posts() causes the wp_query object to generate a new SQL query using our parameters and ignores the other parameters it receives via the URL (page number etc).

The proper way is to send the parameters in the URL together with our parameters and this can be done by including the variable $query_string in the call to query_posts(). When doing this way the quoted portion of the argument must begin with an ampersand (&).
The code now looks like this

<?php
if (is_home()) {
query_posts($query_string."&cat=-3");
}
?>

Another technique is to use a code like this inside the Loop.
<?php if (in_category('3') && is_home() ) continue; ?>

I’ve not tested this code myself, but looking at it i think it should work fine.

For a detailed information on what the query_posts() is capable of doing, visit this wordpress codex page

Leave a Reply

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


four + = 10

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>