How to set cookie in wordpress?

2019-03-04 14:22发布

问题:

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).

回答1:

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.



回答2:

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.