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.

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

add_filter('template_redirect', 'force_404_override' );
function force_404_override() {
	parse_str($_SERVER['QUERY_STRING'], $qs);

	$force404 = Array("some-spammy-query", "another-spammy-query");
	foreach ($qs as $key => $value) {
		if (in_array($key, $force404)) {
			status_header( 404 );
			include( get_query_template( '404' ) );