Last-Modified Header and 304 Responses for Posts
Sends a Last-Modified header with each post's update time and answers repeat visits from crawlers and browsers with "304 Not Modified", saving bandwidth and crawl budget.
Opens WPIDE on
Code
add_action( 'template_redirect', function () {
if ( ! is_singular() || is_user_logged_in() || is_preview() || headers_sent() || post_password_required() ) {
return;
}
$post = get_queried_object();
$modified = (int) get_post_modified_time( 'U', true, $post );
// A new approved comment also counts as a change.
if ( $post->comment_count > 0 ) {
$latest = get_comments( array( 'post_id' => $post->ID, 'status' => 'approve', 'number' => 1, 'orderby' => 'comment_date_gmt', 'order' => 'DESC' ) );
if ( $latest ) {
$modified = max( $modified, (int) strtotime( $latest[0]->comment_date_gmt . ' UTC' ) );
}
}
if ( ! $modified ) {
return;
}
header( 'Last-Modified: ' . gmdate( 'D, d M Y H:i:s', $modified ) . ' GMT' );
$since = isset( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ? strtotime( sanitize_text_field( wp_unslash( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) ) : false;
if ( $since && $since >= $modified ) {
status_header( 304 );
exit;
}
}, 1 );
Notes
Only for logged-out visitors on single posts and pages. Sidebar or menu changes do not update the date, so leave this off if those change often.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.