WP-Mix

A fresh mix of code snippets and tutorials

Exclude category in WordPress

Ever wanted to exclude a category in WordPress? Turns out it’s pretty easy to do without having to install another plugin.

Exclude category in WordPress

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

To exclude category from main page change is_feed to is_home. Or if you want to exlude for both feed and main page, change if ($query->is_feed) { to if ($query->is_feed || $query->is_home) {

Add the following to your theme’s functions.php file:

function exclude_category($query) {
	$query->set('cat','-1');
	return $query;
}
add_filter('pre_get_posts','exclude_category');

If you want to exclude multiple categories, replace the second line with this:

$query->set('cat','-1,-2,-3');

Conditional category exclusion

What if you only want to exclude the category from something specific, like say your feeds? Easy, just a little modification to the previous technique:

function exclude_category($query) {
	if ($query->is_feed) {
		$query->set('cat','-1');
	}
	return $query;
}
add_filter('pre_get_posts','exclude_category');

Here’s an example of excluding a category only on the home page:

function exclude_category($query) {
	if (is_home()) {
		$query->set('cat','-1');
	}
	return $query;
}
add_filter('pre_get_posts','exclude_category');

Alternate method

Here is another way to exclude a category from within the WordPress loop:

<?php if (in_category('1')) continue; ?>

This instructs WordPress to skip any posts in category “1”. Here is another way of writing the condition:

<?php if (!in_category('1')) {
 	// do something for categories that aren't ID = 1
} else {
	// skip any posts from category with ID = 1
	continue;
} ?>

Another alternate method

Lastly, you can instruct the WordPress loop to exclude specific categories:

<?php $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
query_posts($query_string . '&cat=-1&paged=$paged'); ?>

In addition to query_posts(), you can use WP_Query with similar syntax.

Learn more

Digging Into WordPressWordPress Themes In DepthWizard’s SQL Recipes for WordPress