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.
This is great, thanks so much!
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
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.
Yikes. My screen just went white when adding this snippet to the functions.php file…
Ctrl + Z!
Please send me your functions.php file to support@nicethemes.com
I had the same white problem, 🙁
Hi Daniel, what problem? Please ensure that your text editor doesn’t change the quotation marks, or the question marks for php.
My bad, made a typo. It’s working great right now. Thanks
No worries 🙂