How to exclude categories from your WordPress home page.

Quite often, clients ask me to exclude one or more categories from their site home page. Surprisingly, there’s no chance to set this from the WordPress admin section. That’s why, some time ago, I wrote the following function:

<?php

function nice_exclude_cat( $query ) { 

   if ( $query->is_home() && $query->is_main_query() ) 
        $query->set( 'cat', '-1,-2,-3' );

   return $query; 
}

add_filter( 'pre_get_posts', 'nice_exclude_cat' );

?>

Copy and paste the code above into your theme´s functions.php file and voilá.

For this filter, you can set as many categories as you want (replace ‘-1,-2,-3’ with the IDs of the categories you need to exclude). Please remember to separate them with commas and set the negative sign before the category ID.

This is a great example of hacking WordPress core functionalities using filters. (Note to myself: I need to write about this)

I hope you find it useful.

Comments

9 responses to “How to exclude categories from your WordPress home page.”

  1. kim Avatar
    kim

    This is great, thanks so much!

  2. Justin Avatar
    Justin

    Awesome snippet!

    If I need to apply it to another page, say a “blog” page.

    Would I change is_home to is_blog?

    Any feedback is greatly appreciated 🙂

    Justin

    1. Juanfra Avatar
      Juanfra

      Hi Justin,

      Thanks for the kind words.

      What you can do is change $query->is_home() for is_page_template(‘the-name-of-the-template.php’)

      in your case I imagine is ‘template-blog.php’ 😉

      Best,
      Juanfra.

  3. Justin Avatar
    Justin

    Yikes. My screen just went white when adding this snippet to the functions.php file…

    Ctrl + Z!

    1. Juanfra Avatar
      Juanfra

      Please send me your functions.php file to support@nicethemes.com

  4. Daniel Avatar

    I had the same white problem, 🙁

    1. Juanfra Avatar
      Juanfra

      Hi Daniel, what problem? Please ensure that your text editor doesn’t change the quotation marks, or the question marks for php.

      1. Daniel Avatar

        My bad, made a typo. It’s working great right now. Thanks

        1. Juanfra Avatar
          Juanfra

          No worries 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *