Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.