Return 404 response code for certain query strings in WordPress

When WordPress site owners have been victims of hacking they often suffer consequences by getting blocked by Google or getting warnings from Google about malicious URLs on their site. After cleaning the site, these problems can linger when the URLs are only query strings and not actual URLs because query strings will not trigger a 404 in WordPress. One way of fixing this is to gather all the nasty query strings and then set them up to trigger a 404. Here is a basic script that does just that.

To add query strings to the list that triggers a 404, add them in the “force404” array. In the example below the following URLs force a 404.

mywebsite.com/?some-spammy-query
mywebsite.com/?another-spammy-query

Please note that this script requires a 404 template so make sure your theme has one.



add_filter('template_redirect', 'my_404_override' );
function my_404_override() {
	$qs = $_SERVER['QUERY_STRING'];
	$force404 = Array(
		"some-spammy-query",
		"another-spammy-query"
	);
	if (in_array($qs, $force404)) {
		status_header( 404 );
		nocache_headers();
		include( get_query_template( '404' ) );
		die();
	}
}