18 Nov 2006

Exclude Category in WordPress

This is probably the fastest way to exclude category in WordPress besides using a plugin.

Add the following lines to your WordPress Theme’s template functions.php file (For example, functions.php file for a Theme named “default” would probably reside in the directory wp-content/themes/default/functions.php) or create it as a Plugin by filling the additional Standard Plugin Information:

<?php
function exclude_category( $query ) {
	if ( is_feed() ) {
		$query = set_query_var( 'cat', '-5' );  
	}
	
	return $query;
}

add_filter( 'pre_get_posts', 'exclude_category' );
?>

The code example above is for excluding category ID 5 from feed.

If you want to exclude multiple categories, simply separate the category IDs with commas ( , ) and a dash ( - ) followed by the category ID. For example:

'-5, -6, -7'

To exclude category from main page change is_feed() to is_home(). Or if you want to exclude for both feed and main page, then you would need to replace:

if ( is_feed() ) {

with these line:

if ( is_feed() || is_home() ) {

For more possible page conditions, please refer to the Conditional Tags page in the WordPress Codex.