Sometimes it isn’t always appropriate to have articles from every category to show up on your blog’s homepage. For one reason or another, you may not want posts from one or more categories appearing in the stream of posts. For example, if you are posting frequent updates to your products and showing them in your blog sidebar and for that reason it’s kind of pointless to include these category posts in posts stream too or may be if you are using a category to create a slideshow for your website then you might want to exclude category posts from appearing in blog’s homepage.
Although there are some plugins available in WordPress repository to accomplish this simple task but it is also fairly easy to exclude category posts without any help of a plugin. Fortunately WordPress makes it really easy for us to write a function to exclude category posts from the stream.
Simply paste this code snippet in your theme’s functions.php file to exclude category posts. In this example, the numbers 52 is the category IDs that we want to exclude and make sure to add a minus sign in front of category ID.
// exclude category from wordpress blog
function wcs_exclude_category( $query ) {
if ( $query->is_home ) {
$query->set( 'cat', '-54' );
}
return $query;
}
add_filter( 'pre_get_posts', 'wcs_exclude_category' );
If you want to exclude category posts from multiple categories then you can specify category IDs separated by comma. Here is an example to excluding multiple categories.
// exclude multiple categories from wordpress blog
function wcs_exclude_categories( $query ) {
if ( $query->is_home ) {
$query->set( 'cat', '-54, -73, -97' );
}
return $query;
}
add_filter( 'pre_get_posts', 'wcs_exclude_categories' );