How to Exclude a Category From Your WordPress Homepage

By default, WordPress displays all categories on the blog page. However, sometimes you may not want to display individual categories. Today we show you how you can customize the blog post page with just a few lines of code to exclude single or multiple categories.

Exclude a category from the WordPress blog using PHP #

To exclude the individual categories, we need to add a few lines of code in your child theme. To do this, open the functions.php file located in the root directory of your child theme. At the end of the file, add the following code.

/**
 * Remove a single Category from the Blog Page
 */
function exclude_categories_posts($query){
    if(!$query->is_home() || !$query->is_main_query() ){
        return $query;
    }
    $query->set('cat', '-1');
    return $query;
}

add_filter('pre_get_posts', 'exclude_categories_posts');

Then just replace the ID (-1) with the ID of your category.

Important: Make sure that you put the minus sign (-) in front of the ID.

Of course, the same can be done directly for multiple categories. To do this, change the code as shown in the following example.

/**
 * Remove multiple Categories from the Blog Page
 */
function exclude_categories_posts($query){
    if(!$query->is_home() || !$query->is_main_query() ){
        return $query;
    }
    $query->set('cat', '-1,-2,-3,-4');
    return $query;
}

add_filter('pre_get_posts', 'exclude_categories_posts');

Just replace the IDs (-1,-2,-3,-4,-5) with your category IDs to exclude them from your blog page.

That’s it. We hope this article helped you to hide one or more categories from your blog page.

Hier klicken, um den Beitrag zu bewerten
[Gesamt: 0 Durchschnitt: 0]

One Comment

  1. Avatar of Jak zrobić
    Jak zrobić October 12, 2022 at 12:40 - Reply

    This is what I was looking for. I wanted to exclude 1 category from the search results. There is no such feature inside wordpress itself. Now I know how to deal with it.

Leave A Comment

Title