A
A
Aricus2019-07-25 16:38:37
HTTP Cookies
Aricus, 2019-07-25 16:38:37

Why are cookies not being set in Wordpress?

I write in footer.php in wordpress theme:

setcookie('testing', '123', time() + (86400 * 30), "/");
var_dump($_COOKIE['testing']);

I refresh the page several times, each time it returns null. I tried following the advice from the internet:
add_action( 'init', 'my_setcookie_example' );
function my_setcookie_example() {
  setcookie('testing', '123', 30 * DAYS_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN);
}
var_dump($_COOKIE['testing']);

The result is the same. And inside ajax:
add_action('wp_ajax_changecart', 'changecart_callback');
add_action('wp_ajax_nopriv_changecart', 'changecart_callback');
function changecart_callback() {
  ...
  $cartQuantity = (int)$_COOKIE['cartQuantity'] + (int)$_POST['quantity'] - $cartGoods[(int)$_POST['id']];
  ...
  setcookie('cartQuantity', $cartQuantity, time() + (86400 * 30), "/"); 
  ...
  wp_die();
}

everything works fine, but only inside ajax. If you try to get $_COOKIE['cartQuantity'] on the page, then again it will return null.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Igor Vorotnev, 2019-07-25
@Aricus

From the documentation (bold highlighted what is important):
Because of this, it does not work in footer.php. If you had debug mode and error output turned on, you would see something like:
Further, the example with the init hook works, but there are 2 nuances. First, you have an error - the DAYS_IN_SECONDS constant does not exist, it should be DAY_IN_SECONDS. Next, again we go to the documentation about this parameter (I highlighted in bold what is important):
The time the cookie expires. This is the Unix timestamp, i.e. the number of seconds since the epoch. In other words, it is desirable to set this time using the time() function, adding the time in seconds after which the cookie must expire. Or you can use the mktime() function. time()+60*60*24*30 will set the cookie to expire 30 days. If set to 0 or omitted, the cookie will expire when the session ends (when the browser is closed).
In code language, this would be:

function my_setcookie_example()
{
  setcookie(
    'testing',
    '123',
    time() + 30 * DAY_IN_SECONDS, // вот так должно быть
    COOKIEPATH,
    COOKIE_DOMAIN
  );
}
add_action( 'init', 'my_setcookie_example' );

Secondly, from the same documentation (I highlighted in bold what is important):
That is, yours var_dump($_COOKIE['testing']);will work only after a reboot, and on the first try - NULL and:
Notice: Undefined index: testing in /Users/Ihor/Code/playground/wp-content/themes/playground/functions.php on line 134
.
RTFM .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question