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
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.
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: