SEO PHP Beginner

Send a Last-Modified Header on Posts and Pages

Send each post's last modified date as an HTTP header, which crawlers and caches use to check for changes.

Tested on WordPress 7.1 PHP 8.3 No plugin needed Updated
functions.php 6 lines
add_action( 'template_redirect', function (): void {
	if ( ! is_singular() || is_user_logged_in() || post_password_required() || headers_sent() ) {
		return;
	}
	header( 'Last-Modified: ' . get_post_modified_time( 'D, d M Y H:i:s', true ) . ' GMT' );
} );

Where to add this

Recommended A code snippets plugin Survives theme changes and is easy to switch off.
Child theme At the end of your child theme's functions.php file.
Must-use plugin As a .php file in wp-content/mu-plugins, starting with <?php.

Always add PHP to a staging site first, or have FTP or file manager access ready, so you can undo it if something goes wrong.

Crawlers and caches can ask “has this page changed since last time?” if the server tells them when it last changed. WordPress doesn’t send that date for normal pages. This snippet sends it on single posts and pages.

How it works

On template_redirect, once WordPress knows which post it’s showing, the snippet sends a Last-Modified header in the HTTP date format, in GMT, using the post’s modified time. It skips logged-in users and password-protected posts.

Things to watch

  • The header uses the post’s own modified time. Changes to your theme, menus or widgets don’t update it.
  • Caching plugins may send their own header. Check your response headers to make sure there’s only one.

How to test it

Open a post and look at the response headers in DevTools. You should see Last-Modified with the post’s update date.

This website uses cookies to enhance your browsing experience and ensure the site functions properly. By continuing to use this site, you acknowledge and accept our use of cookies.

Accept All Accept Required Only