I need to setup a cookie, however Chrome lately seems to accept them only through HTTPS. The "setcookie" function I use works everywhere except Chrome. If I move to HTTPS, it results as properly set up.

I tried to understand how WordPress works then, checking https://developer.wordpress.org/reference/functions/wp_set_auth_cookie/ and copied a bit of its parameters.

the final code is

$secure = (is_ssl() && 'https' === parse_url(get_option('home'), PHP_URL_SCHEME)); 
setcookie($name, $value, $expiration, COOKIEPATH, COOKIE_DOMAIN, $secure, true);

This is still not working though, what am I missing?

  • Where are you trying to hook this function?
    – Howard E
    Commented Aug 26, 2021 at 9:59
  • Is not a matter of hooks, I'm creating a cookie in an AJAX call performed by frontend users
    – a-coder
    Commented Aug 26, 2021 at 12:48
  • you can't use php setcookie after headers have been sent. use javascript to set the cookie.
    – Howard E
    Commented Aug 26, 2021 at 13:32
  • Probably I was not clear: the AJAX call is handled in the "init" hook, way before headers. The setcookie() system perfectly works, it's just a Chrome block if website is not using HTTPS. However, since WP login (cookie-based, as far as I know) works ... how to achieve the same result?
    – a-coder
    Commented Aug 26, 2021 at 14:19
  • setcookie only requires (name, value). With that said, how can an ajax call being on the frontend happen before init? Ajax is a frontend action, which must by nature happen after the page is rendered. You should probably include more of your code and function for this to make sense.
    – Howard E
    Commented Aug 26, 2021 at 14:44


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.