I'm trying to set up, when a specific page/url is visited that a cookie is set and saved.

So far I've tried this:

add_action('init', 'set_cookie', 1);

function set_cookie(){

  if ( $currentURL == 'https://25dni.si/delovanje-uma/' ) :

    if ( ! isset( $_COOKIE['opt_in'] ) ) :
        setcookie( 'opt_in', has_opt_in, time()+31556926);

    endif;

  endif;

}

Now, when I visit the specific URL, cookie is detected, but when I move on to another page, cookie is gone.

How can the cookie be saved?

I'm pretty new to this, please help me understand.

Thank you!

I'm surprised it works at all since $currentURL is not defined in the function nor declared as a global.

Look at the documentation for setcookie(). You did not declare a path for the cookie so try this:

setcookie('opt_in','opt_in', time()+31556926, '/');

That will set the cookie for the entire domain, if that's what you want to do.

  • Even if I do this, cookie isn't detected on the main page. It still shows only on the specific URL ... I checked the documentation, but still can't figure it out :/ – Alex Dec 1 at 11:34

I've used this and it works:

 add_action('init', 'optin_cookie', 1);

 function optin_cookie(){

   $currentURL = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];

   if ( $currentURL == 'https://25dni.si/delovanje-uma/' ) :

    setcookie( 'opt_in', has_opt_in, time()+31556926, '/');

   elseif ( $currentURL != 'https://25dni.si/' ) :

     if ( ! isset( $_COOKIE['opt_in'] ) ) :

     endif;

    endif;

 }

I'm sure there is a much more elegant way to do it, but this got it working for me ...

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.