Exclude categories from WordPress Search Query

We had an unusual request from a client today, which was to exclude two categories form the WordPress search results. Never being ask this before we quickly found an action in the WordPress codex that allows you to exclude items from the query that is being submitted.

Below is the example on how to exclude categories from the search results:

function excludeCatsFromSearchResults( $query ) { if ( $query->is_search ) { $query->set( 'cat', '40,3' ); // category ids to exclude } return $query; } add_action( 'pre_get_posts', 'excludeCatsFromSearchResults' );

This action can be used for much more than excluding categories. For example if you have a custom post type that you want to change the number of articles to show just chnage your query to this

function excludeCatsFromSearchResults( $query ) { if ( is_post_type_archive('movie') ){ $query->query_vars['posts_per_page'] = 50; return $query; } } add_action( 'pre_get_posts', 'excludeCatsFromSearchResults' );

Comment below if you have any questions or would like to see another example using the pre_get_posts filter.