Exclude category in search

Posted in: Newsmag
Post count: 108

Hi

How can i exclude category ID 87 in search results? There are some posts that are restricted and can only registered members can view them.

Thank you

Post count: 6600

Hi,

Try this code snippet in your functions file and add there the category id you want to exclude:

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

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

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

This is tested so it should work fine for you also.

Thanks

  • This reply was modified 11 years by Lucian.
Post count: 108

brilliant! Thank you!

Post count: 10

Hello Lucian,

I am bringing up his tread one more.
I apologize for my misunderstanding, but where exactly does the category id number has to be placed within the code You provided?

Thank You!

Post count: 23312

Hello 1234.LV

Please look at this -> http://screencast.com/t/LhFoAYwOvN

Thanks.

Post count: 10

Hello Catalin,

Thanks for the help!
But it doesn’t seem to be working. Maybe I have put the code in the wrong functions.php code line?:
http://www.screencast.com/users/mrbubble/folders/Default/media/4861c417-8a00-4d9d-82f4-477f9e3cc01e

Thanks!

Post count: 23312

Hello 1234.LV,

If you want to exclude some categories you will have to use the minus symbol before the number.

Thanks.

Post count: 10

In the end I added the category’s name.

function exclude_category_from_search($query) {
if ($query->is_search) {
$cat_id = get_cat_ID(‘uncategorized’);
$query->set(‘cat’, ‘-1’);
}
return $query;
}
add_filter(‘pre_get_posts’,’exclude_category_from_search’);

It worked!

Thanks!

Viewing 8 posts - 1 through 8 (of 8 total)
You must be logged in to reply to this topic.