I have two categories that I want to exclude from my search results, so far without luck.

I have tried adding the following piece of code but it didn't work.

$search_query = query_posts(array('category__in' => array(-22, -21)));

Here is my current code.

global $query_string;

$query_args = explode("&", $query_string);
$search_query = array();

foreach($query_args as $key => $string) {
    $query_split = explode("=", $string);
    $search_query[$query_split[0]] = urldecode($query_split[1]);
} // foreach

$searchq = new WP_Query($search_query);

while ($searchq->have_posts()) : $searchq->the_post();

1 Answer 1


You can use pre_get_posts action to exclude categories from search query.

function wcs_exclude_category_search( $query ) {
  if ( is_admin() || ! $query->is_main_query() )

  if ( $query->is_search ) {
    $query->set( 'cat', '-22, -21' );

add_action( 'pre_get_posts', 'wcs_exclude_category_search', 1 );

You should paste this code in your theme's functions.php file.

  • Thank you for your answer. I have tried similar solutions that I found on the internet but none seem to work. I'm starting to think maybe it's a problem with my search form. Will report back if I find out anything.
    – Swen
    Sep 22, 2014 at 15:13
  • I ended up fixing my issues by removing "$query->" from "$query->is_search". I did this because the unwanted categories would still show up if you entered an empty search query.
    – Swen
    Sep 22, 2014 at 15:31
  • 1
    Excuse my ignorance, but what's the objective of if ( is_admin() || ! $query->is_main_query() ) ?
    – drabello
    Jul 2, 2017 at 4:57
  • Ok great, and how would this work with categories from custom post types? Thanks!
    – Yuri
    Nov 13, 2020 at 11:34
  • @Yuri don't post replies as new solutions, and post new questions as new questions not comments wordpress.stackexchange.com/questions/ask
    – Tom J Nowell
    Nov 13, 2020 at 13:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.