If changed from title in WordPress
I am trying to enable 304 If Modified Since HTTP header
WordPress on my site. After doing a lot of work on google, I came across a site where the author said to put the following line at the very end of the wordpress file wp-config.php
. Here is the line of code:
header("Last-Modified: " . the_modified_date());
Now the author has said that it is so. I don't need to do anything to achieve 304 If Modified Since HTTP header
. But after that I tested the HTTP header using the site http://httpstatus.io/ and here is a screenshot of my header:
(check the red marked section). The last modified value of the BLANK header.
After that, I thought it might be a problem with the function the_modified_date()
, so I tried the function as well get_the_modified_date()
. But there is no result.
At the very end, I created a small shortcode function to check if these functions work or not and repeated it inside the shortcode. When I used the shortcode, I can clearly see that the functions are working fine, but for some reason they are sending an empty string to 304 If Modified Since HTTP header
.
Please guys help me fix this issue. I don't know how to achieve this.
PS: My site is www.isaumya.com
source to share
the_modified_date()
is the template tag to be used inside the loop, so it is not for you.
WordPress provides an action and filter to enable or change HTTP headers:
-
send_headers
action -
wp_headers
filter (I didn't find a link in the codex)
But it won't work for this purpose. For example, the following code doesn't work:
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 request is not being created at the moment, nor in wp_headers
. So it is_singular()
returns false
, get_queried_object_id()
returns NULL
, and there is no way to get the modified time of the current message.
A positive solution is to use an template_redirect
action hook as suggested by Otto in this question (tested and works):
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) );
}
}
}
note
The answer to the question @cybmeta on here . I am just passing the answer here so that if anyone searches for an answer here he / she will find it. All credits are sent to @cybmeta .
source to share