Excluding Posts from Blog Page in WordPress

Ok, this one seemed to trip me up quite a bit when I had a client ask to exclude a certain category from the main blog page in WordPress. For example, if you have a category of “news” or a category of “events” that you don’t want to show up on your main blog page you’ve designated in WordPress just add this snippet to your theme’s functions file at the bottom before the closing php tag “?>”,  if there is one in your theme.

// Exclude news and events category posts from specified blog page

function exclude_category($query) {
if ( $query->is_home() ) {
$query->set(‘cat’, ‘-6 -7’);
}
return $query;
}
add_filter(‘pre_get_posts’, ‘exclude_category’);

Note that in this case, category 6 was my “news” category and category “7” was my “events” category. So, in this query I’m simply prefixing the numerical id with a minus to exclude it from the results.

The full details can be found on the good ol’ WordPress Codex here – http://codex.wordpress.org/Class_Reference/WP_Query

Hopefully that’ll help some poor soul searching for this seemingly simple task out there.

Cheers!

Leave a Reply

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