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.

Got a project? Let's talk.

From website design & SEO through to custom WordPress plugin development. I transform ideas into dynamic, engaging, and high-performing solutions.
Subscribe to get the latest insights & updates in the world of web and how it impacts your business and website.
© 2024 Phil Kurth  |  All rights reserved.