How to Exclude a Category From Your WordPress Homepage

Marc Wag­ner

June 22, 2022

1 min read|

By default, Word­Press dis­plays all cate­go­ries on the blog page. Howe­ver, some­ti­mes you may not want to dis­play indi­vi­du­al cate­go­ries. Today we show you how you can cus­to­mi­ze the blog post page with just a few lines of code to exclude sin­gle or mul­ti­ple cate­go­ries.

Exclude a category from the WordPress blog using PHP #

To exclude the indi­vi­du­al cate­go­ries, we need to add a few lines of code in your child the­me. To do this, open the functions.php file loca­ted in the root direc­to­ry of your child the­me. At the end of the file, add the fol­lo­wing 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 cate­go­ry.

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

Of cour­se, the same can be done direct­ly for mul­ti­ple cate­go­ries. To do this, chan­ge the code as shown in the fol­lo­wing exam­p­le.

/**
 * 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 cate­go­ry IDs to exclude them from your blog page.

Tha­t’s it. We hope this artic­le hel­ped you to hide one or more cate­go­ries from your blog page.

88e86fcb816eff22bc917094df2862d8dd5c0e978b333e6dd5f36f808990c261 96

Arti­kel von:

Marc Wag­ner

Hi Marc here. I’m the foun­der of Forge12 Inter­ac­ti­ve and have been pas­sio­na­te about buil­ding web­sites, online stores, appli­ca­ti­ons and SaaS solu­ti­ons for busi­nesses for over 20 years. Befo­re foun­ding the com­pa­ny, I alre­a­dy work­ed in publicly lis­ted com­pa­nies and acqui­red all kinds of know­ledge. Now I want to pass this know­ledge on to my cus­to­mers.

Hast du eine Fra­ge? Hin­ter­lass bit­te einen Kom­men­tar
  1. blank
    Jak zro­bić Octo­ber 12, 2022 at 12:40 — Rep­ly

    This is what I was loo­king for. I wan­ted to exclude 1 cate­go­ry from the search results. The­re is no such fea­ture insi­de word­press its­elf. Now I know how to deal with it.