# 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.

- Type: PHP
- Runs: Frontend only
- Category: [SEO](https://wpide.com/library/category/seo/)
- Tags: http-headers, crawling, caching
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/seo-last-modified-header/

## Code

```php
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 use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Last-Modified Header and 304 Responses for Posts" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
