How to Exclude Category Posts in WordPress – Tutorial with Code that Works

July 4th, 2009

It is astounding how much worthless advice can be found on the web. If you are not a seasoned coder, you can find yourself facing simple dilemmas which can turn into a nightmare if solutions offered on various websites don’t lead to actual solution of your problem, only cause more problems and frustration. And that’s what I found to be the case with excluding posts from one particular category (or more categories) from your WordPress powered blog’s main page. I have been contacted by several people asking me for help excluding category posts from their WordPress blog, each of which was tearing their hair out as their tried many suggested solutions you can find across the web, but they either don’t work at all, or exclude the category, but break something else (mostly bust your title tags which are the most important part of your on page SEO).

Why Exclude Categories in WordPress?

There are several reasons why you may need to exclude category posts from your WordPress blog. One of the WP blogs I have built used a “Video of the Day” feature. The blog normally focused on different subject matter, but the owner wanted to offer his readers an extra feature to keep them entertained so he introduced the Video of the Day page. He would be posting one cool video each day and had them all listed on a dedicated page, however he didn’t want these Video of the Day posts mixed up with main topic of his website. So he was looking for a code to add to the WordPress theme which would exclude all posts from Video of the Day category from his main blog page. It turned up being a pain in the neck finding out the tutorial or ready to use code that would safely and reliably exclude that category.

How to Exclude Category Posts in WordPress – Tutorial

To exclude posts from a particular category in WordPress you first need to create that category and then mark down the category ID. It is very easy to do, just follow these steps:

  • go into Posts > Categories
  • create New Category (skip this step if you are excluding a category which already exists)
  • click on Category you want to exclude
  • mark down the ID number of the category – you can see it by taking a look at the ULR of the page in your browser’s address bar. It is the number at the end of the URL, right after the equal sign. The URL should end with something like this &cat_ID=xx where xx is a number (note, it could be a single, double or triple digit number, depending on how many categories your WordPress blog has. Some blogs could get four or five digit number. Just mark down the number in full as it appears after the equal sign)
  • go into Appearance > Editor and click on the file called “Theme Functions” (functions.php) listed under the Templates on the right hand side
  • paste the code below into your functions.php theme file, right before “?>” part at the end of it, replace “xx” with your category ID you have made note of and click “Update File”.

Code to Exclude Category Posts in WordPress

Use this code to paste in your functions.php file. It should be pasted right before the ?> part which should be the part of the exiting code. Replace “xx” in the code provided with Category ID you have made note of before hand. This is absolutely essential as you must let WordPress know which category you want to exclude for it to work. If you forget about it and paste it as it is provided below with xx instead of a Category ID, your category poses will NOT be excluded! Make sure you keep the minus sign (-), only replace “xx”, nothing more.

function exclude_category($query) {
if ( $query->is_home() ) {
$query->set('cat', '-xx');
}
return $query;
}
add_filter('pre_get_posts', 'exclude_category');

Excluding Multiple Categories in WordPress

Sometimes you may wish to exclude more than one category from your main blog page. To do it is again very easy, you just need the Category ID of each category you wish to exclude. Post that Category ID along with the minus sign right before it in the same space as other category IDs, but separate them with spaces. So the final code would look something like this:

$query->set('cat', '-9 -53 -98 -484');

An example of code above would exclude posts from categories with following IDs: 9, 53, 98, 484

How to Exclude Categories from Archive Pages in WordPress

Sometimes you may also want to exclude category posts from archive pages. Or you may wish to have a category excluded from both Archives and Main Blog Page. Both of these are easy. The code for it would be as follows:

To exclude category posts from Archive pages, replace second line of code with following code:

if ( $query->is_archive ) {

To exclude category posts from both Archive pages and Main Blog Page, replace second line of code with following code:

if ( $query->is_home || $query->is_archive) {

That’s it. I have written this post in a way so even a new blogger could understand it and hopefully it helps. These codes definitely work with WordPress 2.7 through 2.8 but will also work on most older versions of WordPress.

 

Incoming search terms:

  • wordpress exclude category
  • exclude category wordpress
  • exclude category
  • wordpress exclude category from blog
  • exclude category from blog wordpress
  • exclude categories
  • exclude categories wordpress
  • query post exclude category
  • exclude category from page wordpress
  • Exclude Posts From Some Category

Also Check Out:

53 Responses to “How to Exclude Category Posts in WordPress – Tutorial with Code that Works”

Frank

Thanks… very helpful amd works like a charm

Josh

This is fantastic. I can’t even begin to tell you how long it’s taken to find the correct way of doing this.

downloadcity

Thanks for the wonderful information!

Reino

Any way to exclude posts from a query in stead of a whole category?

Nicolas TAFFOREAU

Hello !

Good tuto thx but i have a problem. If i use this code the category is exclude on home page and on galery page. I need this category on my galery page. Do you have an idea ?

Thx, Nicolas.

deanswa

Thanks! you just saved me another two weeks going thru those plug-ins. Amen to your intro!

Kim

You are a lifesaver! I looked everywhere for this solution. Found a few that claimed theirs would work, but nothing else did. Perfect! Thank you very, very much.

Aracely

This code is not working for me. Maybe I am putting it in the wrong place? Can you please be more specific when saying that it should go before the ?>

Mark Davies

this code doesn’t work, any chances of a rewrite soon??

David Yiadom

Hey there..

Nice tutorial, easy to understand and works like it should.

Thanks!

Andrew

Thanks for the information you have shared with this post. I’ve been searching for more information about wordpress in which I like to be an expert on that application.

Great thanks to you!

Nog Jenkins

It worked for me too. I know exactly what you mean about sifting through google results to pass by the wrong solutions. Thanks!

Jesse

I’ve been looking for this for months. Thanks!

Jesse

Despite including any of the following

$query->is_archive || $query->is_category

This function excludes categories from queries sitewide. How to fix this?

Friends Links Forum

Very Nice Thanks For Sharing

Bjoern

Hey!

It works perfect. Thanks for this smart code! Great!

ddddddddd

how can i pagging posts excluding last 6 posts

Andreas

Thanks a lot for sharing your code. It works fine on my site.

Cheers!
A.

Y8

The Loop is used by WordPress to display each of your posts. Using The Loop, WordPress processes each of the posts to be displayed on the current page and formats them according to how they match specified criteria within The Loop tags. Any HTML or PHP code placed in the Loop will be repeated on each post. When WordPress documentation states “This tag must be within The Loop”, such as for specific Template Tag or plugins, the tag will be repeated for each post.

For example, among the information The Loop displays by default: the Title (the_title()), Time (the_time()), and Categories (the_category()) for each post. Other information about each post can be displayed with the appropriate Template Tags or (for advanced users) by accessing the $post variable, which is set with the current post’s information while The Loop is running.

SamTrotz

Hi i would like to exclude two categories from the archives which is now really easy because of this article (thanks btw) but! i want to see these excluded categories when i click on them in the categories widget. how can i do that please?

Javi A.

Wow !
Awesome !

Now I got a question.
Is it possible to exclude of showing one category to non registered visitors?

Thank you in advance

Robert Jay

Thanks… ^^ it helps a lot!

James Hobson

Nice. thanks.

shelly

“It is astounding how much worthless advice can be found on the web. …”

Precisely! I spent a couple of hours futzing with a variety of approaches offered out there and only managed to exclude categories from the home page — is_archive, is_month, is_author etc did not work. Until I copied your code. Fabulous. Thank you so much!

Paul

Let me be the first grateful person in 2011 to say thank you for this little gem! Thanks :-)

David lee- encuestas remuneradas

the code works perfect! thanks for making bigger internet with your post

rebekah

thank you!! i love that it just works! that’s more than i can say for most wp hacks :D

toscalini

Thank you so much. This is a time saver form me. Works fine.

dancerinthesand

Thank you so much. I needed this to include only certain categories in archives, and it works just fine!

James

Thanks for the help. I couldn’t figure out how to fix my categories.

Duerrbi

Since update to Wprdpress 3.1 it seems the query_post function does not work anymore.

Dan S

this didn’t work for me, i’ve tried everything but can’t figure out how to exclude categories from my homepage! :(

Mark

Hi guys,

I have updated the code to work with v3.1 – I believe this tiny addition will avoid problems with category exclusions in WordPress 3.1 and later.

The only addition are parenthesis after is_home. Try this and let me know if it works or not for you.

Mark

Dan

Thanks Mark. It was actually my own error, my theme had it’s only exclude categories function over-riding the WP default. Heh

Charl

You nailed it, “so much worthless advice “. Thank God I found your post!

Shane

This is a great little bit of code. I have one problem though – on the site I’m working on the home page is a static page and a page called ‘blog’ is set as the page to display the WP blog posts. For the reason is_home doesn’t work. Any idea what I would need to put in there to exclude the categories from that blog page?
Thanks!

Hailey M

Thank you SO much for this! It is exactly as you said… so many bad tutorials/advice for this issue out there, but nothing as simple as this. Thank you for the clean and concise advice!!

Pat

I have the same situation as Shane (2 posts above), where my home page is static and blog posts are on a page called ‘blog’. I tried changing first line
if ( $query->is_home() ) {
to
if ( $query->is_blog() ) {
but suddenly every page became blank white page. Any advise how to make this work on non-home pages would be appreciated.

Matt Beram

This is not working for me. Maybe it doesn’t work with the latest version of wordpress

Pat

Although I couldn’t get this code to work properly with my non-home page blog, I found a plugin that works great for me (using WP 3.1) called ‘Ultimate Category Excluder’.

Ash

thank you..
it really works:)

barli

it doesn’t work, please help

jobs in jamshedpur

I tried and it worked can you also tell me about how to set seo friendly urls in wordpress.

katrina kaif wallpapers

This is not working for me. Maybe it doesn’t work with the latest version of wordpress

Luna

Друзья , подскажите , кто знает или сталкивался.

Есть потребность приобрести подвеску с бриллиантом массой более карата, но знаю , что это стоит безумных денег и мне не по карману.

Но слышала , что существуют облагороженные бриллианты, которые ничем не отличаются от обычных, но стоят меньше в

два раза.

Кто-нибудь вообще держал такие в руках, они правда прекрасны ?

Diane

This is not working for me. Am new at this I will keep trying, Thank you.

Vision Without Glasses

Finally I know how to exclude category posts in WP. Thanks for sharing.

Emedoutlet

Nice tut to read first thing in the morning. Further examples of how easy it is to fiddle and customise WordPress with little understanding of php.

Thanks!

erik

Oh please guys, help me. Ik have a excluded all categries but now I get a “Page not found error 404″.
I don`t want any blog post on the home page.
Is this possible?
Thank you sooo much for your help.
Cheers Erik.

Dorothy

This was fantastic! I use Thesis theme so instead of entering the code in the function.php file, use the custom_function.php file, placing it at the bottom. Worked like a charm!

Erik, you need to go to settings on your WP dashboard (on the left) and click on Reading. At the top you can choose to have your blog roll as your home page, or a static Page as your home page.

Cheers!

Laur A. Bundberg

Great guide, it takes a little time to imlement it and actually works.

Aj

Great guide, good work.

SLT-A77

Io senza dubbio desiderato a salire un riconoscimento per essere mezzo per apprezzare abbiamo per tutti un contributo glorioso siamo stati qui esposti. Il mio curiosare internet allargata è subito stata famosa con grandi strategie di andare oltre con i miei amici e la famiglia. vorremmo dimostrare che la maggior parte di noi visitatori essenzialmente sono stati senza dubbio santificato ad esistere in un villaggio cospicuo di persone davvero più diluito con sentori redditizio. ci sentiamo veramente grati di avere rilevato le tue pagine web così come atteggiamento sfacciato per la maggior parte in modo qualcosa di più straordinaria festa minuti di una massa qui. Grazie ancora per noi tutti dettagli.

Leave a Reply