Eric
Eric

Reputation: 161

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.

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.

Upvotes: 4

Views: 5378

Answers (2)

laxandrea
laxandrea

Reputation: 77

You can hook before the actual query is run:

    function my_404( $query ) {
        if ($query->queried_object_id == 813) {
            header('HTTP/1.1 404 Not Found');
            die('Testing123');
        }
    }
    
    add_action( 'pre_get_posts', 'my_404' );

Upvotes: 1

TimoStaudinger
TimoStaudinger

Reputation: 42460

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' );

Upvotes: 7

Related Questions