Jesse Lawson

buy me a coffee ☕ / home / blog / tutorials / portfolio / hire me! / contact

Jun 24, 2013 - webdev

How to Hide a Category in WordPress

Do you want to keep articles up and running but omit them from queries? Here’s a quick way to exclude categories from every loop on your site.

The Problem

I have about fifty different posts that I wrote a few years ago that are not related to web development or WordPress at all — in fact, they were for a different blog project altogether — and I don’t want them showing up on my site at all. If people click on external links and arrive at my page I still want them to be able to read the articles, but for anyone whose first visit to Lawsonry is after May 2013, I want only web development and WordPress content to show up.

I’m looking for:

  • Total exclusion of one or many categories from every query on my blog. I want it to look like they don’t exist at all.
  • Accessible links to the articles belonging to the categories I’m hiding. Just because I’m hiding them doesn’t mean I want to cut off the people who still access these articles.
  • A quick way to implement this.

The Solution

There are plenty of plugins that exclude categories for you, but I’m not a fan of using plugins for simple features (and neither should you be) so I created a custom callback function to hook into WordPress. Specifically, we target the pre_get_posts hook, and call a function that will omit our categories from all query variables on our site (don’t worry — it’s a lot easier than I make it out to be).

Copy and paste the following code in your functions.php file:

add_action('pre_get_posts', 'hide_these_categories' );

function hide_these_categories( $wp_query ) {
  //$excluded = array(35); // Exclude category with ID=35
  $excluded = array(1, 2, 3); // You can exclude more than one category, too
  // Keep the categories showing up in the administration panel
  if( !is_admin() ) {
    set_query_var('category__not_in', $excluded);
  }
}

Don’t forget to change the above category IDs to those on your blog that you want to hide!