Answer the question
In order to leave comments, you need to log in
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']);
add_action( 'init', 'my_setcookie_example' );
function my_setcookie_example() {
setcookie('testing', '123', 30 * DAYS_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN);
}
var_dump($_COOKIE['testing']);
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();
}
Answer the question
In order to leave comments, you need to log in
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' );
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
. Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question