Exclude Category Wordpress

Exclude A Single Category In WordPress

Because not all content is main content.

WordPress websites have never been one size fits all. Customizing is how we cram in branding and functionality to fit everybody’s needs. Recently I’ve been getting requests from clients who want to create a post on their WordPress site which doesn’t automatically post to the front page. Since WordPress is designed as blogging software to highlight new content, I will have to customize the theme to accommodate their needs to exclude a single category in WordPress.

Categories are designed as a classification tool for organizing the website content. However, as stated above, maybe a site owner needs to use a category to represent other content related to the site’s subject but not necessarily be apart of the main content. I’ve found 2 ways to get around excluding a single category in WordPress; Adding PHP code or using a plugin.

Plugin Method To Exclude A Single Category In WordPress

Really, use a plugin and save yourself the headache of finding category id’s and digging through PHP files if you aren’t building the theme from the ground up. Here are two which work beautifully:

WordPress PHP To Exclude A Single Category In WordPress

As we stated before, one size does not fit all. If you need to add code and not install a plugin, below is the cleanest way I’ve come across to prevent posts in a specific categories from displaying in the main post loop.

Finding a useful snippet using WordPress’ API action pre_get_posts which will allow for additional pre-query logic from the David Walsh Blog. This was hands down the easiest code to use. First you will need to find the category ID you are trying to exclude. Then you can add this code to the functions.php file since it is a WordPress action.

// Prevent category "Community Events" from appearing in the main post loop
function nocommunityevents($query) {
	if($query->is_home() && $query->is_main_query()) {
		$query->set('cat', '-181'); // 181 = Community Events Category ID *replace*
add_action('pre_get_posts', 'nocommunityevents');

To add more than one category just use a comma:

$query->set('cat', '-181,-265');



Posted in Plugins, WordPress and tagged , , , , , , .

Leave a Reply