Theme's function.php文件中的Wordpress条件标签


Wordpress Conditional Tags in Theme's function.php file

我试图在我的主题的function.php文件中设置HTTP响应头,因此我试图将过期时间设置为单个帖子页面6小时和其他20分钟。

我需要检查当前访问的url是一个单一的帖子页面。为此,我使用wordpress条件标签,他们不工作。

下面是我的代码:
function add_custom_http_headers($headers) {
    $headers['Cache-Control'] = 'public';
    $now = time();
    if(is_single())
        $then = gmstrftime("%a, %d %b %Y %H:%M:%S GMT", $now + 60*60*6);
    else
        $then = gmstrftime("%a, %d %b %Y %H:%M:%S GMT", $now + 20*60);
    header("Expires: $then");
    header("Last-Modified: ".gmstrftime("%a, %d %b %Y %H:%M:%S GMT", $now));
    return $headers;
}
add_filter('wp_headers', 'add_custom_http_headers');

似乎我们无法访问我试图使用它们的条件标签。请帮助我找到当前页面类型的解决方案,即它的post页面/主页/有/没有在functions.php或任何其他合适的代码点使用条件标签来实现此头设置模块。

您还可以在header.php文件中这样设置标题:

$now = time();
    if(is_single())
        $then = gmstrftime("%a, %d %b %Y %H:%M:%S GMT", $now + 60*60*6);
    else
        $then = gmstrftime("%a, %d %b %Y %H:%M:%S GMT", $now + 20*60);
    header("Expires: $then");
    header("Last-Modified: ".gmstrftime("%a, %d %b %Y %H:%M:%S GMT", $now));
    header("Cache-Control: public");

如果要查找当前页面类型,请使用get_post_type()is_single()函数不用于检查帖子类型,它用于检查您是否在单个帖子页面上。