Blacklist for search in Wordpress

Blacklist for search in Wordpress. Yes, there are plugins for almost every problem. But in most cases you don't need to install a plugin so that you can extend Wordpress according to your needs.

Blacklist for search in Wordpress
Photo by Luca Bravo / Unsplash

Yes, there are plugins for almost every problem. But in most cases you don't need to install a plugin so that you can extend Wordpress according to your needs.

One customer wanted to have a blacklist to exclude certain terms from the search. When searching for a term from the blacklist, the user should be redirected to the 404 page.

Here is the code to copy into functions.php:

add_action('wp', 'check_search');
function check_search() {
	global $wp_query;
	if (!$s = get_search_query())
		return false;
	if (preg_match('/\b(stopword1|stopword2)\b/i', $s)) {
		$wp_query->set_404();
		status_header(404);
		get_template_part(404);
		exit();
	}
}

For a handful of terms this solution is quick and easy. If there are more terms, you could work with Advanced Custom Fields (ACF) to manage the terms.