WordPress exclude categories from homepage

If you use posts within WordPress to generate content, such as Frequently Asked Questions or Help Guides, it’s quite often the case that you don’t want these to appear on the posts page of your blog.

Instead of having to re-create the whole query, you can append a comma separated list of category ID’s  that you want to exclude to the end of the original query and fetch the new data set to be used.

To achieve this, insert a variation of the following into your index or template file specified as the posts page:

<?php if (is_home()) query_posts($query_string.'&cat=-2,-3'); ?>

This should be placed before the loop, therefore ideally just before:

<?php if (have_posts()) : ?>

Adding this line of code will check if the current page is the posts page (is_home) and if so exclude the categories with ID’s 2 and 3. Note here the negation used (-2 and -3), without this the query will include rather than exclude the categories.

If you don’t want to hard code ID values, you could use the get_category_by_slug or get_category_by_path functions to fetch the category ID.

Leave a Reply