Even if you make it works, you are running 3 different queries (get_term
fire a query) in addition to the main query for any request, I don’t think is the right way to do what you want.
I guess that when you send an invalid tag / category / custom tax you don’t find any posts, so why don’t
add_action( 'template_redirect', 'my_page_template_redirect' );
function my_page_template_redirect() {
global $wp_query;
if ( ! (int) $wp_query->found_posts > 0 ) {
$wp_query->set_404();
status_header(404);
nocache_headers();
}
}
Edit
This function return a 404 even if existing taxonomies are passed but with no post. someone can find this good, if not this is an alternative not doing so:
function my_page_template_redirect() {
global $wp_query, $wp;
// this get an array of the query vars in the url
parse_str( parse_url ( add_query_arg( array() ), PHP_URL_QUERY ), $qv);
if ( ! empty( $qv ) ) { // if there are some query vars in the url
$queried = array_keys( $qv ); // get the query vars name
$valid = $wp->public_query_vars; // this are the valid query vars accepted by WP
// intersect array to retrieve the queried vars tha are included in the valid vars
$good = array_intersect($valid, $queried);
// if there are no good query vars or if there are at least one not valid var
if ( empty($good) || count($good) !== count($queried) ) {
$wp_query->set_404();
status_header(404);
nocache_headers();
}
}
}
This function will set the 404 only if one or more invalid query vars (invalid taxonomy names but not only) are in the query.