How to Hide a Category in WordPress Home Page?

hide wordpress categories in homepage

In this blog, you will learn how to hide specific categories from the WordPress home page. You can hide multiple categories at once using ids

I came across a use were in one of my WordPress blogs where I had to hide posts on the home page from a specific category.

I came across few plugins, but I didn’t want to install a WordPress Plugin just for this use case.

After some research, I found the code snippet that implements the functionality I was looking for.

Let’s have a look.

Function To Hide WordPress Categories

In WordPress, there is a function named exclude_category.

So what we have to do is call the function and specify the home page condition with the category ids which we cant to hide.

The following function hides two categories (380 & 415) from the home page.

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

Here is a small explanation.

  1. is_home() function adds the condition to hide the categories only if it is a home page.
  2. -380, -415 are two category ids we want to hide.

Getting WordPress Category Ids To Hide

Getting category ids is pretty simple.

Just edit the category in the WordPress dashboard, and in the URL, you will find the category ID as shown below.

Get wordpress category id

Add exclude_category to WordPress fucntions.php

To implement this, you need to add the code in the functions.php.

Note: If you don’t know what you are doing, please do not edit any WordPress files. If you know what you are doing, then take a WordPress backup before making the changes.

You will find the functions.php in child themes as well as the main theme.

I use the WordPress theme editor to edit the theme files.

Now, paste the following code into the functions.php. Replace 380 and 415 with your category ids. If you want to hide more categories, you can add multiple category ids separated by a comma.

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

Conclusion

I have shown you how to hide WordPress categories from the homepage.

It is always good to use a staging site to test all the code changes.

I wouldn’t recommend making code changes on a Live WordPress site. It could break your site.

You can use the WP-staging plugin to creating WordPress staging in minutes.

Let me know in the comments section if you face any issues with the code.

0 Shares:
Leave a Reply

Your email address will not be published.

You May Also Like