Exclude a category from recent post on home page

by Oscar

To hide posts from category/categories, from showing up on your index page, is easy. You don’t need a plugin for this. Simply add one line of code on your index.php, and BAM! Work!

Go to index.php in your theme folder, find the “while” loop, where the posts are loop through and rendered on the page:

[sourcecode language=”php”]
<?php while ( have_posts() ) : the_post();?>

<?php
// ….
// more codes here, skipping…
// ….
?>

<?php endwhile;?>
[/sourcecode]

And add this line on top of it:

[sourcecode language=”php”]
<?php query_posts(‘cat=-15’); // EXCLUDE COOKING CATEGORY ?>
[/sourcecode]

It basically means skipping category “15”, this is the ID of the category, you can find it out by editing categories, your URL should be something like this:

http:/yourdomain.com/wp-admin/edit-tags.php?action=edit&taxonomy=category&tag_ID=15&post_type=post

tag_ID is your category ID.

Excluding multiple categories is also easy, simply modify the extra line of code to be:

[sourcecode language=”php”]
<?php query_posts(‘cat=-15,-16,-17’); // EXCLUDE COOKING CATEGORY ?>
[/sourcecode]

But that’s not all. if you have Multiple pages on your index page, it will show the same posts regardless page number. (pagination failed using query_post() function) That’s because we need to tell it explicitly the posts on a particular page we want to display, ie. the page number.
Replace the above line with this:

[sourcecode language=”php”]
<?php

// EXCLUDE COOKING/diary CATEGORY
$args = array(
‘cat’ => ‘-15,-1’,
‘paged’ => (get_query_var(‘paged’)) ? get_query_var(‘paged’) : 1,
);

query_posts($args);

?>
[/sourcecode]

There are actually a few more arguments you can use for more specific filtering using query_posts function, such as post type. Google it!

Leave a Comment

By using this form, you agree with the storage and handling of your data by this website. Note that all comments are held for moderation before appearing.