我正在尝试在我的 WordPress 站点中启用 304 If Modified Since HTTP header
。做了很多谷歌搜索后,我找到了一个网站,作者说将以下行放在 wordpress wp-config.php
文件的最后。这是代码行:
header("Last-Modified: " . the_modified_date());
现在作者说就是这样了。我不需要做任何其他事情来实现 304 If Modified Since HTTP header
。但是在这样做之后,我使用站点 http://httpstatus.io/ 通过 HTTP header 进行了测试这是我的标题的屏幕截图:
(检查红色标记部分)。最后修改的 header 值为空白。
之后我认为这可能是 the_modified_date()
函数的问题,所以我也尝试了 get_the_modified_date()
函数。但是还是没有结果。
最后,我创建了一个小的短代码函数来测试这些函数是否正常工作,并在短代码中回显它。当我使用短代码时,我可以清楚地看到这些功能运行良好,但由于某种原因将空白发送到 304 If Modified Since HTTP header
。
请大家帮我解决这个问题。我不知道如何实现这一目标。
P.S.:我的网站是www.isaumya.com
最佳答案
the_modified_date()
是一个必须在循环内使用的模板标记,这就是它不适合您的原因。
WordPress 提供了一个操作和过滤器钩子(Hook)来包含或修改 HTTP header :
-
send_headers
action wp_headers
过滤器(我没有在 codex 中找到引用)
但它不适用于此目的。例如,下一个代码不起作用:
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) );
}
}
}
为什么?
目前主要的 wp 查询未构建,wp_headers
过滤器中也未构建。所以,is_singular()
返回false
,get_queried_object_id()
返回NULL
,没有办法得到修改后的值当前帖子的时间。
一个可能的解决方案是使用 template_redirect
Action Hook ,正如 Otto 在 this question 中所建议的那样(测试和工作):
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) );
}
}
}
请注意
问题由 @cybmeta 回答在here .我只是在这里分享答案,这样如果有人在这里寻找答案,他/她就会找到。所有功劳归功于@cybmeta .
关于php - 如果在 WordPress 中修改自 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27589282/