How to trigger 404 for custom query var?

There is an action specifically for this:

function my_parse_query( $wp_query ) {
    if ( $wp_query->get( 'my_custom_var' ) > 42 ) {
        $wp_query->set_404();
        status_header( 404 );
    }
}
add_action( 'parse_query', 'my_parse_query' );

That should load the 404.php template in your theme, if you have it. Otherwise, it will fall back to index.php.

This will also trigger a HTTP 404 status code.

For more information see parse_query.

Leave a Comment