How to Exclude a Category from the WordPress Homepage

Home » Snippets » How to Exclude a Category from the WordPress Homepage
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 a WordPress user looking to customize your homepage by excluding certain categories? By default, WordPress displays posts from all categories on the homepage. However, there may be cases where you want to exclude certain categories from the homepage to maintain a specific focus or showcase certain content. In this article, we will guide you through the process of excluding categories from your WordPress homepage, allowing you to tailor it to your specific needs.

					function wpturbo_exclude_category_from_homepage($query) {
    if ( $query->is_home() && $query->is_main_query() ) {
        $query->set( 'cat', '-3' ); // Replace 3 with the ID of the category you want to exclude
    }
}
add_action( 'pre_get_posts', 'wpturbo_exclude_category_from_homepage' );
				

The code snippet provided aims to exclude a specific category from being displayed on the homepage of a WordPress website. This can be useful if you want to filter out certain posts or content from the main feed.

The function wpturbo_exclude_category_from_homepage() is defined to modify the main query for the homepage. It checks if the current query is for the homepage and is the main query being executed.

if ( $query->is_home() && $query->is_main_query() ) {

The condition ensures that we only target the main query on the homepage and not any other secondary queries or pages.

Inside the condition, we use the set() method of the $query object to modify the query parameter 'cat'. The 'cat' parameter is used in WordPress to specify the category ID(s) of the posts to be queried.

In this case, we set the cat parameter to '-3', replacing 3 with the ID of the category that you want to exclude from the homepage. The - sign before the category ID ensures that this category is excluded from the query.

$query->set( 'cat', '-3' );

This line of code modifies the query to exclude posts from the category with the ID of 3 from being displayed on the homepage.

Finally, the wpturbo_exclude_category_from_homepage() function is hooked into the pre_get_posts action. This action fires right before the main query is executed, allowing us to modify the query parameters before fetching the posts.

add_action( 'pre_get_posts', 'wpturbo_exclude_category_from_homepage' );

By hooking the function to this action, the modified query will be executed whenever the homepage is requested, resulting in the exclusion of the specified category from the homepage’s post feed.

Make sure to replace the 3 in the code snippet with the actual ID of the category you want to exclude from the homepage.

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