How to set cookie in wordpress?

2019-03-04 13:35发布

I want to set cookie in wprdpress but its not working.This is my code

add_action('init', 'set_new_cookie');
    function set_new_cookie() {
        setcookie('cart_item','some value', time() + (86400 * 30), "/");
    }

but this is not working. Actually init hook is not working.I am trying to do ajax request here(page visitors are not logged in).

2条回答
Juvenile、少年°
2楼-- · 2019-03-04 14:14
setcookie('cart_item',$carts,time() + (86400*30),'/');

Its working fine for me. / at the last is to set cookie for whole site. Remove / to set cookie for particulat directory only.

查看更多
再贱就再见
3楼-- · 2019-03-04 14:15

Well if this is the sequence your code runs then you need to switch the function and the call to it. Now you are calling the function before you initiated it.

查看更多
登录 后发表回答