the_modified_date()
is a template tag that must used inside the loop, that is why it is not wokring for you.
WordPress provide a action and filter hook to include or modify HTTP headers:
But it doesn’t work for this purpose. For example, the next code is not working:
add_action( 'send_headers', 'cyb_add_last_modified_header' );
function cyb_add_last_modified_header() {
//Check if we are in a single post of any type (archive pages has not modified date)
if( is_singular() ) {
$post_id = get_queried_object_id();
if( $post_id ) {
header("Last-Modified: " . get_the_modified_time("D, d M Y H:i:s", $post_id) );
}
}
}
Why?
The main wp query is not build at this moment, neither in wp_headers
filter. So, is_singular()
returns false
, get_queried_object_id()
returns NULL
and there is no way to get the modified time of the current post.
A posible solution is to use template_redirect
action hook, as suggested by Otto in this question (tested and working):
add_action('template_redirect', 'cyb_add_last_modified_header');
function cyb_add_last_modified_header($headers) {
//Check if we are in a single post of any type (archive pages has not modified date)
if( is_singular() ) {
$post_id = get_queried_object_id();
if( $post_id ) {
header("Last-Modified: " . get_the_modified_time("D, d M Y H:i:s", $post_id) );
}
}
}