Development & EngineeringJun 22, 2022
How to Exclude Individual Categories from Your WordPress Blog Page
By default, WordPress displays all categories on the blog page. However, there may be times when you want to hide specific categories. Today, we will show you how to customize the blog post page with just a few lines of code to exclude one or more categories.
Excluding a Category from the WordPress Blog Using PHP
To exclude individual categories, we need to add a few lines of code to your child theme. To do this, open the functions.php file located in the main directory of your child theme. At the end of the file, add the following code.
/**
* Remove a single Category from the Blog Page
*/
function exclude_categories_posts($query){
if(!$query->is_home() || !$query->is_main_query() ){
return $query;
}
$query->set('cat', '-1');
return $query;
}
add_filter('pre_get_posts', 'exclude_categories_posts');
Simply replace the ID (-1) with the ID of your category.
Important: Make sure to place the minus sign (-) before the ID.
The same can be done directly for multiple categories. To do this, modify the code as shown in the following example.
/**
* Remove multiple Categories from the Blog Page
*/
function exclude_categories_posts($query){
if(!$query->is_home() || !$query->is_main_query() ){
return $query;
}
$query->set('cat', '-1,-2,-3,-4');
return $query;
}
add_filter('pre_get_posts', 'exclude_categories_posts');
Simply replace the IDs (-1,-2,-3,-4,-5) with your category IDs to exclude them from your blog page.
That's it! We hope this article has helped you exclude one or more categories from your blog page.