Sometimes there may be certain categories or tags that you don’t want to appear in your WordPress search results. You could use a plugin to exclude posts that are in these categories or tags, or you could just add a little snippet to your site.
Excluding Categories
To exclude posts that are in a specific category from your WordPress search, simply use the following snippet:
add_filter( 'pre_get_posts', 'snippetpress_search_exclude_categories' ) function snippetpress_search_exclude_categories( $query ) { if ( $query->is_search && !is_admin() ) { $query->set( 'cat','-5, -10, -12' ); } return $query; }
In the above snippet, any posts that are in categories 5, 10 or 12 will not show in the search results. Just replace these numbers with the IDs of the categories you want to exclude. You can have as many or as few categories as you need.
Excluding Tags
To exclude posts that have a specific tag from your WordPress search, simply use the following snippet:
add_filter( 'pre_get_posts', 'snippetpress_search_exclude_tags' ) function snippetpress_search_exclude_tags( $query ) { if ( $query->is_search && !is_admin() ) { $query->set( 'tag','-2, -9, -11' ); } return $query; }
In the above snippet, any posts that have tags 2, 9 or 11 will not show in the search results. Just replace these numbers with the IDs of the tags you want to exclude. You can have as many or as few tags as you need.
Where to add the snippet?
Whichever snippet you choose to use, you should place it at the bottom of the functions.php file of your child theme. Make sure you know what you’re doing when editing this file. Alternatively, you can use a plugin such as Code Snippets to add the custom code to your WordPress site. If you need further guidance on how to add the code, check out our post on How to Add WordPress Snippets.
Leave a Reply