I want to save product id in an array when user opens a product page, and then save that array in a cookie. This is my code:
if(is_product()) {
if(isset($_COOKIE['recent'])) {
$data = unserialize($_COOKIE['recent']);
$product_id = get_the_ID();
if(!in_array($product_id, $data)) {
array_unshift($data, $product_id);
if(count($data) > 8) {
array_pop($data);
}
setcookie('recent', serialize($data), time()+(3600*24*7), "/");
}
echo "SET";
}else{
$data = array();
$product_id = get_the_ID();
array_unshift($data, $product_id);
setcookie('recent', serialize($data), time()+(3600*24*7), "/");
echo "DIDNT SET";
}
print_r($data);
}
Those echos and print_r is for debugging purposes. So if it is a product page, I check whether cookie is already set, if yes, then I just want to add product ID to the array if it is already there and update the value. And if cookie is not set, I'm creating a new array and then printing content of $data.
The problem is, that all, except one product page works fine. For example I can browse through products and see that it prints out the same array over and over again, but one product page has its own array of IDs, which is array of one element - that product element. That product page has no different URL from others. same pattern: website.com/product/productname/
It seems like it has its own scope. Even tough I used "/" for the domain, so I guess it should be the same across all the website?
What is wrong here?