How to Exclude the Default Category in WordPress

Home » Snippets » How to Exclude the Default 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 looking to exclude the default category from your WordPress website? The default category is typically named "Uncategorized" and is assigned to posts that are not assigned to any other category. By excluding this category, you can ensure that all of your posts have specific and relevant categories assigned to them. In this article, we will show you how to easily exclude the default category from your WordPress site.

					function wpturbo_exclude_default_category( $query ) {
    if ( $query->is_main_query() && ! is_admin() ) {
        $query->set( 'cat', '-1' ); // Replace 1 with the ID of the default category
    }
}
add_action( 'pre_get_posts', 'wpturbo_exclude_default_category' );
				

The code snippet provided helps in excluding the default category from the main query of a WordPress website. This can be useful in scenarios where you want to exclude posts that are assigned to the default category from being displayed on the frontend.

To achieve this, we create a function called wpturbo_exclude_default_category() that takes in the $query variable. This function will be responsible for modifying the main query of the page.

Inside the function, we have a conditional statement that checks if the current query is the main query ($query->is_main_query()) and if it’s not in the admin area (! is_admin()). This ensures that the modification is only applied to the main query on the frontend of the website.

The line $query->set( 'cat', '-1' ); is where the actual modification happens. Here, we use the set() method of the $query object to specify that we want to exclude a specific category from the query. In this case, we are using -1 as the value, which indicates the ID of the default category. You should replace 1 with the ID of the default category in your WordPress installation.

Once the query modification is done, we hook the wpturbo_exclude_default_category() function into the pre_get_posts action using the add_action() function. This ensures that the function is executed before the main posts query is performed, allowing us to modify it accordingly.

By using this code snippet, the default category will be excluded from the main query on the frontend, resulting in posts assigned to the default category not being displayed. This can be particularly useful if you have a specific use case where excluding the default category is required.

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