I am using this code to set a cookie in a wordpress site. When I place this code in header.php, it works perfectly. But when I place this code in Separate template file, it does not work. Header File Code: (Before HTML Tag)

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)

<?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

有帮助吗?

解决方案 2

The problem was I did not mention the path in the function. The code was creating cookie for the particular page. Here is the corrected function:

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

其他提示

You can't set a cookie after output has started. Cookies and all other HTTP header information can only be set before the output has started. Output can mean anything from an empty space before PHP tags to actual HTML content.

You shouldn't ever have to put cookies in a body. All logic should be done before starting output of templates.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top