如果在WordPress中修改了自标题

时间:2014-12-21 12:18:40

标签: php wordpress .htaccess seo http-headers

我正在尝试在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标头进行了测试,这是我标题的屏幕截图:

enter image description here (查看红色标记部分)。最后修改的标头值为BLANK。

之后我认为这可能是the_modified_date()函数的一些问题,所以我也尝试了get_the_modified_date()函数。但仍然没有结果。

最后,我创建了一个小的短代码函数来测试这些函数是否正常工作,并在短代码中回显它。当我使用短代码时,我可以清楚地看到功能正常工作但由于某种原因发送空白到304 If Modified Since HTTP header

拜托,伙计们,帮我解决这个问题。我不知道如何实现这一点。

P.S。:我的网站是www.isaumya.com

1 个答案:

答案 0 :(得分:0)

the_modified_date()是一个必须在循环中使用的模板标记,这就是为什么它不适合你。

WordPress提供了一个操作和过滤器钩子来包含或修改HTTP头:

但它并没有为此目的而工作。例如,下一个代码不起作用:

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()会返回falseget_queried_object_id()会返回NULL,并且无法获得当前帖子的修改时间。

一个可行的解决方案是使用template_redirect动作钩子,正如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

相关问题