PHIL KURTH

Email

Forcing a 404 in WordPress

If you ever find yourself in a position where you need to force a 404, this can be done by hooking into the wp action hook and setting the 404 status on the $wp_query object via the set_404() object method. Doing this will ensure WordPress checks for the 404.php template file and uses it, if available.

add_action('wp', function()
{
      /** @var WP_Query $wp_query */
      global $wp_query;
      $wp_query->set_404();
});

Why use the wp hook?

The wp hook is where the $wp_post and $wp_query variables are set up with the queried post data. You don’t have to use this particular hook, but you do have to use a hook somewhere between the wp hook and the loading of the actual markup template.

One last thing…

If you liked this article, I'd be incredibly grateful if you tweeted about it.

Also, I don't send emails often but when I do, I try to fill them full of useful goodies. If you like code snippets & dev tips, join my mailing list. There's no catch but I'll probably want to tell you about any new plugins & tools I build.