How to Hide Posts in the Uncategorized Category in WordPress

Home » Snippets » How to Hide Posts in the Uncategorized Category in WordPress
0

Created with:

Visibility: 

public

Creator: WPTurbo Team

Customize with WPTurbo AI
X

Add Snippet To Project

New Project
Add To Existing Project

Are you tired of seeing "Uncategorized" as the default category for your WordPress posts? Do you wish you could hide these uncategorized posts from appearing on your site altogether? In this article, we will show you how to easily hide posts in the uncategorized category and keep your WordPress site organized and clutter-free.

					function wpturbo_hide_uncategorized_posts($query) {
    if ($query->is_home() && $query->is_main_query()) {
        $query->set('cat', '-1');
    }
}
add_action('pre_get_posts', 'wpturbo_hide_uncategorized_posts');
				

The code snippet provided above allows you to hide posts in the "uncategorized" category on the homepage of your WordPress website. Let’s break down how this snippet works.

First, we define a new function called wpturbo_hide_uncategorized_posts(). This function is responsible for modifying the main query of the homepage to exclude posts in the "uncategorized" category.

The if ($query->is_home() && $query->is_main_query()) condition checks if the current page is the homepage and if this is the main query being executed. This ensures that the code only runs on the homepage and not on any other page or custom query.

Inside the condition, we use the $query->set('cat', '-1') method to modify the query. The set() method is a powerful tool that allows us to set or modify different parameters of the query. In this case, we set the cat parameter to -1 which means excluding the "uncategorized" category.

The last step is to hook the wpturbo_hide_uncategorized_posts() function into the pre_get_posts action. This action allows us to modify the query before it is executed. By hooking into this action, our function will be called before the homepage query is processed.

Once the function is hooked into the action, whenever the homepage is loaded and the main query is executed, the code will modify the query to exclude posts in the "uncategorized" category. As a result, any posts in the "uncategorized" category will not be displayed on the homepage.

It’s important to note that this code snippet only affects the homepage, and specifically the main query on the homepage. If you want to hide posts in the "uncategorized" category on other pages or custom queries, you may need to modify the code accordingly.

Register an account to save your snippets or go Pro to get more features.