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;

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.