I am trying to set a cookie in wordpress using an hook in functions.php, but the cookie values come out empty. How can I set the cookie getting the values from the URL ($_GET)?
(Edit) I only need this cookie to be set at an specific page, so I wrapped it on an if statement. The cookie is now set correctly. But when I move to another page and try to get the cookie it’s not set anymore! Any Ideas why this could be happening?
(Edit 2) I fixed this by setting the cookie path to “/”.
function set_cookie(){
if(is_page('hotel')){
$destinationType = 'city'; //'city';
$destinationCode = $_GET["dcode"]; //'lon';
$checkinDate = $_GET["date_in"]; //date('2013-08-05'); // '2006-05-10';
$checkoutDate = $_GET["date_out"];
$date1 = strtotime($checkinDate);
$date2 = strtotime($checkoutDate);
$datediff = $date2 - $date1;
$duration = floor($datediff / (60 * 60 * 24));
//Create Search Object
$search = array();
$search[0] = $destinationType;
$search[1] = $destinationCode;
$search[2] = $checkinDate;
$search[3] = $checkoutDate;
$search[4] = $duration;
//Create Rooms Object
$packages = array();
$npack = intval($_GET['numpack']);
for ($j = 0; $j < $npack; $j++) {
$packages[$j][0] = $_GET['rtype' . ($j + 1)];
$packages[$j][1] = 1; //$_GET['nroom' . ($j + 1)];
$packages[$j][2] = $_GET['cot' . ($j + 1)];
if ($packages[$j][2] == null) {
$packages[$j][2] = '0';
}
for ($k = 0; $k < intval($_GET['children' . ($j + 1)]); $k++) {
$packages[$j][3][$k] = $_GET['achild' . ($j + 1) . '_' . ($k + 1)];
}
}
//Complete Search Object to cookie
$searchObject = array($search, $packages);
setcookie('searchobject', json_encode($searchObject), time() + 3600, "/");
}
}
add_action('get_header', 'set_cookie');
If the cookie is there, but it’s empty, I suggest checking if
json_encode()
does it’s job. It returnsnull
whenever it encounters some character not of its liking. A nice way to check isjson_last_error()
, which you have to call somewhere afterjson_encode()
.You may do a full step-by-step checking on your problem:
$searchObject
contains what I wantjson_encode()
properly produces json dataIn my answer I assumed the first two are ok.