How to Exclude a Category From Your WordPress Homepage

Marc Wagner, June 22, 2022

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.

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

Avatar of Marc Wagner
Marc Wagner

Hi Marc here. I'm the founder of Forge12 Interactive and have been passionate about building websites, online stores, applications and SaaS solutions for businesses for over 20 years. Before founding the company, I already worked in publicly listed companies and acquired all kinds of knowledge. Now I want to pass this knowledge on to my customers.

Similar Topics

Comments

  1. 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.

Leave A Comment