Skip to content

Instantly share code, notes, and snippets.

@jcchouinard
Created January 19, 2022 04:29
Show Gist options
  • Save jcchouinard/900e0c0626323f4180b58ba2e1930d87 to your computer and use it in GitHub Desktop.
Save jcchouinard/900e0c0626323f4180b58ba2e1930d87 to your computer and use it in GitHub Desktop.
Add Last-Modified HTTP header in Wordpress
/**
* Set the Last-Modified header for visitors on the front-page
* based on when a post was last modified.
*/
add_action( 'template_redirect', function() use ( &$wp )
{
// Only visitors (not logged in)
if( is_user_logged_in() )
return;
// Target front-page
if( ! is_front_page() )
return;
// Don't add it if there's e.g. 404 error (similar as the error check for feeds)
if( ! empty( $wp->query_vars['error'] ) )
return;
// Don't override the last-modified header if it's already set
$headers = headers_list();
if( ! empty( $headers['last-modified'] ) )
return;
// Get last modified post
$last_modified = mysql2date( 'D, d M Y H:i:s', get_lastpostmodified( 'GMT' ), false );
// Add last modified header
if( $last_modified && ! headers_sent() )
header( "Last-Modified: " . $last_modified . ' GMT' );
}, 1 );
/* add last-modified HTTP header to blog posts */
add_action('template_redirect', 'theme_add_last_modified_header');
function theme_add_last_modified_header($headers) {
global $post;
if(isset($post) && isset($post->post_modified)){
$post_mod_date=date("D, d M Y H:i:s",strtotime($post->post_modified));
header('Last-Modified: '.$post_mod_date.' GMT');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment