Last-Modified header for visitors on the front-page
It’s useful to see how the Last-Modified header is added to the feeds, in the wp::send_header()
method.
If we want to be able to use is_front_page()
, then the filters wp_headers
or send_header
are probably applied to early.
We could instead use the template_redirect
hook to target the front-page, before the headers are sent and after is_front_page()
is ready.
Here’s an example:
/**
* 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 );
Here we used the core PHP functions header()
, headers_list()
and headers_sent()
and the WordPress core function get_lastpostmodified()
The Etag header could be added here too as the md5 of the last modified date.
We can then test it from the command line with e.g.:
# curl --head https://example.tld
or just use the shorthand parameter -I
to only fetch the HTTP headers.