Exclude words while searching in WordPress
Did you know that when you’re using the search boxes on your WordPress site, you can narrow down the results by providing words that you don’t want included? That’s right! This method works both on the front end (theme-provided search bar, search widget, etc), as well as on the back end (post listing screens, etc), and is available since WordPress v4.4
All you need to do is prefix the words you don’t want included with a simple hyphen/dash “-“!
For example, if you are searching on a WordPress website for chicken recipes, you’ll most probably type in the search box:
However, you get an overwhelming number of chicken soup recipes. Soup is definitely not what you’re looking for, so all you need to do is type:
Great, but now you’re flooded by fried chicken recipes, and again, it isn’t what you’re looking for. Now sweat:
chicken -soup -fried
That’s all there is to it really!
Just remember that WordPress searches the title, the content and the excerpt of each post, so if you exclude a word that exists in any of those places, the post will not be included in the results.
Customizing the exclusion character
WordPress v4.7.0 introduced a new filter that allows us to change the hyphen/dash to any character we want. Why we might want that? Because we might have content that contains dashes and we need to search for them!
This is how you can change the hyphen to, say, an exclamation mark:
All you need to do is hook to the wp_query_search_exclusion_prefix filter and return the character you want as the prefix. Note that it must be a single character, as only the first characters of each word are checked against the prefix.
Turning it off
You might have your reasons for turning this search exclusion feature off. We don’t and we won’t judge. It’s your installation after all, and you are the administrator!
While there’s no native filter for turning this feature off, we can simply exploit the aforementioned wp_query_search_exclusion_prefix filter to our advantage. We can just return an empty string! As mentioned, the prefix is checked against the first character of each search term. Setting the prefix as an empty string, it will always fail to recognise it as an exclusion, effectively turning it off.
Did you know the search exclusion feature existed? Do you employ it in your daily routine? Do you have any related tips you wanna share? Let us know in the comments below.