Mika MAtikainen

Apr 15, 2020 · 4 min read

How to Trigger 404 Template in WordPress?

The first way to use the theme’s 404 template to serve a 404 “Not Found” response, we can hook into wp with our function like so:
function wps_trigger_404() 
{
    global $wp_query;
    $wp_query->set_404();
    status_header(404);
}
add_action(‘wp’, ‘wps_trigger_404′);
Then inside the function, we declare the global variable and set the 404 on the WP query object using the set_404() method. Lastly, we set the 404 header response using WordPress status_header() function. The end result of this code is to serve a 404 HTTP response using the theme’s 404.php template file.

Second Method

The second method uses pre_get_posts action hook to set the 404 error and serve up the theme’s 404.php template. It looks like this:
[code lang=”php”] function shapeSpace_trigger_404($wp_query) { if ($wp_query->is_main_query()) { $wp_query->set_404(); status_header(404); } } add_action(‘pre_get_posts’, ‘shapeSpace_trigger_404’); [/code]
For this method, we are use pre_get_posts to modify the main WP query. The main difference between the first and second methods is the hook that is used and getting of the $wp_query variable. In the first method we declare it as a global variable; in the second method it is passed to the function via the pre_get_posts hook.

Subscribe To Our Newsletter

Join our mailing list to receive the latest news and updates from our team.

You have Successfully Subscribed!

Share This