I am trying to set a cookie, based on a GET variable from a page.

The page URL looks like: mysite.com/?my_var=somevalue

I'm trying this, but can't see what I'm doing wrong..

// make 'my_var' available as get_query_var('my_var')..
function add_query_vars_filter($vars){
    $vars[] = "my_var";
    return $vars;
add_filter('query_vars', 'add_query_vars_filter');

add_action('init', 'my_setcookie');

// take the query_var 'my_var' and set it as cookie 'my_cookie'
function my_setcookie() {
    setcookie('my_cookie', get_query_var('my_var'), strtotime('+1 day'));

Would love a little help with this!

Thanks in advance.

  • possible duplicate of Setcookie works on admin but not front end
    – gmazzap
    May 24, 2014 at 17:53
  • You want to set cokkie on every page wherever you get that my_var or on specific page like homepage or post page. :)
    – ksr89
    May 24, 2014 at 18:02
  • Thanks G.M. - I'll try that - looks as though it may work for this.. May 24, 2014 at 18:04
  • Thanks ksr89 - I just want to set it for one specific page. May 24, 2014 at 18:05

1 Answer 1


On the page where you want to set the cookie write this code and check

if(get_query_var('my_var') == 'somevalue'){
    setcookie('my_cookie', get_query_var('my_var'), strtotime('+1 day'));

If we go with your code then it will set coookie on every page who having query variable


  • 1
    Thanks ksr89 - that works, as long as I can edit the page template for that page, to set the cookie before any output.. However, I don't want to use a custom edited template page, so I think so I think I am limited to either a plugin (beyond my skills..), or site-wide functions available in the functions.php - So I did a combination of yours and the page that G. M. mentioned: May 26, 2014 at 14:23

Your Answer

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

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