简体   繁体   English

PHP setcookie()函数无法在Wordpress模板文件中使用

[英]PHP setcookie() function not working in Wordpress Template File

I am using this code to set a cookie in a wordpress site. 我正在使用此代码在wordpress站点中设置cookie。 When I place this code in header.php, it works perfectly. 当我将此代码放在header.php中时,它完美地运行。 But when I place this code in Separate template file, it does not work. 但是,当我将此代码放在单独的模板文件中时,它不起作用。 Header File Code: (Before HTML Tag) 头文件代码:(在HTML标记之前)

if (isset($_COOKIE['City'])) {
setcookie('City', 0, -(3600*3600*3600));
setcookie('City', "Edmonton2", 3600*3600*3600);
}
else {
setcookie('City', "Edmonton", 3600*3600*3600);
}

WP Template File Code: (Code is before the get_header() function) WP模板文件代码:(代码在get_header()函数之前)

<?php 
if (isset($_COOKIE['City'])) {
setcookie('City', 0, -(3600*3600*3600));
setcookie('City', "Edmonton2", 3600*3600*3600);
}
else {
setcookie('City', "Edmonton", 3600*3600*3600);
}
?>
<?php
/*
    Template Name: Community Landing Page
*/
get_header(); ?>

Any help would be highly appreciated. 任何帮助将受到高度赞赏。 Thanks & Regards 感谢和问候

You can't set a cookie after output has started. 输出开始后,您无法设置cookie。 Cookies and all other HTTP header information can only be set before the output has started. Cookie和所有其他HTTP标头信息只能在输出开始之前设置。 Output can mean anything from an empty space before PHP tags to actual HTML content. 输出可以表示从PHP标记之前的空白空间到实际的HTML内容。

You shouldn't ever have to put cookies in a body. 你不应该把饼干放在体内。 All logic should be done before starting output of templates. 所有逻辑都应在开始输出模板之前完成。

The problem was I did not mention the path in the function. 问题是我没有提到函数中的路径。 The code was creating cookie for the particular page. 代码正在为特定页面创建cookie。 Here is the corrected function: 这是更正后的功能:

setcookie('City', "Edmonton43003", (time()+3600), "/");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM