How to Hide Posts from a Certain Category on the WordPress Homepage

How to Hide Posts from a Certain Category on the WordPress Homepage
How to Hide Posts from a Certain Category on the WordPress Homepage
WordPress works very well as a blogging platform, but unfortunately it does not have a quick short-post feature like Weibo or Twitter. If you create a category specifically for this kind of brief post, the homepage can end up looking cluttered and disorganized. According to various tutorials online, there are several ways to solve this problem. I chose the simplest and most convenient one: modifying the content in index.php.
First, you need to find the ID number of the category. The category I did not want to show on the homepage was named "闲言碎语," but its internal ID is not the same as its name. To see the category ID, go to the WordPress admin dashboard, then open Posts → Categories. There you can see all your post categories. Move the mouse over a category name—just hover, do not click—and look at the status bar at the bottom of the browser. You should see something like category&tag_ID=3. The number after tag_ID is the category's ID. Write down the ID of the category you do not want to display on the homepage.
Next, go to Appearance → Editor, where you can edit the template files of your site theme. In the upper-right corner you can choose which theme to edit. By default it should be the currently active theme; editing other themes is useless. In the list of theme files below, find the homepage template index.php. Generally speaking, the homepage uses a loop to iterate through posts. You should be able to find code such as if ( have_posts() ) : and/or while ( have_posts() ) : the_post();. Add one line of code after the latter to exclude posts from the category you do not want shown on the homepage:
if (in_category('1') && is_home()) continue;
Replace the 1 inside the parentheses with the ID of the category you want to hide. If you want to block multiple categories, just copy this line several times.
If your theme uses a structure where each line is written separately, you can also add the following code to functions.php, which is a better approach:
function exclude_category( $query ) {
if ( $query->is_home() && $query->is_main_query() ) {
$query->set( 'cat', '-6, -7' );
}
}
add_action( 'pre_get_posts', 'exclude_category' );
Here, 6 and 7 are the category IDs you want to exclude.


