Skip to content

Instantly share code, notes, and snippets.

@fliespl
Forked from MikeNGarrett/functions.php
Created December 31, 2023 17:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fliespl/135ee383838a5203cbfdac0b9546092e to your computer and use it in GitHub Desktop.
Save fliespl/135ee383838a5203cbfdac0b9546092e to your computer and use it in GitHub Desktop.
Set cache headers on WordPress 404 pages.
<?php
/**
* Force cache headers on 404 pages and prevent WordPress from handling 404s.
*
* @param bool $preempt determines who handles 404s.
* @param obj $wp_query global query object.
*/
function change_404_headers( $preempt, $wp_query ) {
if ( ! is_admin() && ! is_robots() && count( $wp_query->posts ) < 1 ) {
header( 'Cache-Control: max-age=30000, must-revalidate' );
header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', strtotime( '+5000 minutes' ) ) . ' GMT' );
header( 'Last-Modified: ' . gmdate( 'D, d M Y H:i:s', strtotime( '-5000 minutes' ) ) . ' GMT' );
$wp_query->set_404();
status_header( 404 );
// prevents the default 404 from firing.
return true;
}
return $preempt;
}
add_filter( 'pre_handle_404', 'change_404_headers', 2, 99 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment