Send 404 status code on a specific WordPress page?

I need to send a 404 status code on a specific page in WordPress. The page is not using the 404.php template. Preferably, I would like to do it within my theme files, and not using .htaccess.

Here is what I have that’s not working.

Read More
function my_404() {
  if ( is_page( 813 ) ) {
    header('HTTP/1.1 404 Not Found');
    echo 'Testing123'; //This outputs fine, so I know the code is running on the correct page
  }
}
add_action( 'wp', 'my_404' );

If successful, the page would look the exact same, except running it through a website analyzer would tell me it’s returning a 404 code. However, using this code, it still returns 200 no matter what.

Related posts

1 comment

  1. Try this, that should get you the expected result:

    function my_404() {
      if ( is_page( 813 ) ) {
        global $wp_query;
        $wp_query->set_404();
        status_header(404);
        nocache_headers();
      }
    }
    
    add_action( 'wp', 'my_404' );
    

Comments are closed.