WP-Mix

A fresh mix of code snippets and tutorials

WordPress Trigger 404.php Template

Recently I needed a programmatic way to trigger a 404 error in one of my free WordPress plugins. Fortunately WordPress makes it very easy to do. This quick tutorial explains two different ways to make it happen.

First method

The first way to use the theme’s 404 template (i.e., 404.php) to serve a 404 “Not Found” response, we can hook into wp with our function like so:

function shapeSpace_trigger_404() {
	
	global $wp_query;
	$wp_query->set_404();
	status_header(404);
	
}
add_action('wp', 'shapeSpace_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:

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

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.

Learn more

Digging Into WordPressWordPress Themes In DepthWizard’s SQL Recipes for WordPress