Caching 404 pages in WordPress

This is to stop WordPress in handling 404, using headers to manage cache expiry. This code should be added to the theme’s functions.php file.

function template_slug_404_cache() {
	if( is_404() ){
		header( 'Cache-Control: max-age=30000, must-revalidate' );
		header( 'Expires: ' . date( 'D, d M Y H:i:s', strtotime( '+5000 minutes' ) ) . 'UTC' );
		header( 'Last-Modified: ' . date( 'D, d M Y H:i:s', strtotime( '-5000 minutes' ) ) . 'UTC' );        
	}
}

/**
 * Redirect a 404 to a cache page
 *
 * @return void
 */
function template_slug_404_redirect() {
	if ( is_404() ) {
		header( 'Location:' . site_url( '/404' ) );
		exit();
	}
}
add_action( 'template_redirect', 'template_slug_404_cache' );

Be sure that there is a 404.php file on the template directory.

Share