Excluding a Category from the Home Page

This is the code to add/change in the index.php file of your template if you use the method specified in the WordPress codex:

< ?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
< ! -- The following tests if the current post is in category 3. -->
< ! -- If it is not, the code within The Loop is executed as normal. -->
< ! -- If it is, nothing is done until the next post is processed. -->
< ?php if ( !(in_category('3')) ) { ?>

Unfortunately, this doesn’t stop the loop from executing, all it does is stop the post from the specified category from showing up. You may be thinking this is exactly what you want, but, generally, it isn’t. You see, say we set the number of posts to appear on the home page to 10, what happens is, WordPress works through your posts and if any of the last 10 posts is in the category that you don’t want to appear they get included in the count even if they don’t show up. So if seven of the last 10 posts were in the category you want to exclude, you’ll only get three posts on your home page. Not good. There is a simpler method to exclude a category and it doesn’t cause the same counting problems.

Start by going into your admin section, then Manage, then Categories and make a note of the ID number of the category you wish to exclude. Now open up the index.php file of the theme you use (you can do this through Presentation, then Theme Editor if you have set the file properties to allow it, otherwise use a text editor).

Now find the line that says:

< ?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

Note: it may be split over two lines.

Now add:

query_posts($query_string .’&cat=-catID’);

between the ‘:’ and the word ‘while’, where catID is the ID number of the category you want to exclude, so the line looks something like this:

< ?php if ( have_posts() ) : query_posts($query_string .'&cat=-catID'); while ( have_posts() ) : the_post(); ?>

Make sure you put a – (minus) sign in front of the category ID number.

Save and upload if necessary and check it out. You should now be excluding the correct category and getting the right number of posts.