cookies

Set a Cookie in WordPress

Posted

Sometimes you want to detect new users on your site versus returning visitors and display different sorts of information to them. An easy way to do this is to set a cookie.

If you’re doing this via a theme, add this line to your functions.php file:

function set_newuser_cookie() {
	if ( !is_admin() && !isset($_COOKIE['sitename_newvisitor'])) {
		setcookie('sitename_newvisitor', 1, time()+3600*24*100, COOKIEPATH, COOKIE_DOMAIN, false);
	}
}
add_action( 'init', 'set_newuser_cookie');

You can read more about the setcookie function at PHP.net. This will set a new cookie named “sitename_newvisitor” which is set to expire in two weeks. If you changed 1 to 0, the cookie won’t expire.

To display different information to a returning user vs a new user, you could do something like this:

if (isset($_COOKIE['sitename_newvisitor'])) {
     echo 'Welcome back!';
}
else {
     echo 'Hello new visitor!';
}

About Devin

I'm a WordPress developer based in Austin, Texas. Follow my projects on GitHub, or more general WordPress ramblings as @devinsays on twitter.

23 thoughts on “Set a Cookie in WordPress

  1. tom wrote:

    you know your code overflow hidden after cookiepath?

    • Devin wrote:

      Thanks. Looks like code syntax highlighting wasn’t set. I updated it.

  2. Lucian wrote:

    A simple php code with great use in web developing.

  3. Works perfect.
    Please, change setcookie line (expire section) for better readability to this:
    setcookie('sitename_newvisitor', 1, time()+3600*24*100, COOKIEPATH, COOKIE_DOMAIN, false);

  4. Thanks, Devin,
    I was thinking about cookies & WordPress right this morning when still waking up. You made my day. Ciao!

  5. Raquel wrote:

    Hi, nice article! I want to communicate domain and subdomain by cookies, that someone whos looged in domain still logged in domain, i use ur code to read the cookie generated by domain but it doesnt get any information, can u help me please?

  6. Dimitar wrote:

    and how can I pass parameters to the set_newuser_cookie function

    thanks

  7. Onur wrote:

    Hi, thanks for posts.. I like it, but im do not know variable cookie names?

    Example:

    <?php global $posts; $variable_names = get_post_ID();
    setcookie('cookie-'$variable_names)

    After:

    Both are not working

  8. Julian wrote:

    thank you for this great snippet!

    it was great for showing a banner to visitors just one time!!

  9. Jasmine wrote:

    Good cookie snippets there. I actually want to pass parameters to WordPress and then track these in the cookies. How do I pass the parameters to the set_newuser_cookie function through the permalink?

  10. Luca wrote:

    hello,

    to have the cookie not to expire, it’s the duration parameter, the third one, that should be set to 0. in this example the duration parameter is time()+1209600.

    the second parameter, 1, is the value assigned to the cookie itself.

    to have a non expiring cookie one should write something like:


    setcookie('sitename_newvisitor', 1, 0, COOKIEPATH, COOKIE_DOMAIN, false);

    • Shecky wrote:

      @Luca: Setting the duration parameter to zero would make the cookie expire after the session closes.

      There is no way to set a cookie to not expire. Rather you must adjust the time so that it expires at a date far into the future (ie: several years)

      See RFC6265

  11. Nathan wrote:

    Jasmine wrote:
    February 18, 2012 at 6:36 pm
    Good cookie snippets there. I actually want to pass parameters to WordPress and then track these in the cookies. How do I pass the parameters to the set_newuser_cookie function through the permalink?

    I am trying to do the same thing. So far I have:

    function set_cookie_type($dough) {
    if (!isset($_COOKIE['CookieType'])) {
    setcookie(‘CookieType’, $dough, time()+60, COOKIEPATH, COOKIE_DOMAIN, false);
    }
    }
    add_action( ‘init’, ‘set_cookie_type’, 1, 1);
    do_action(‘set_cookie_type’, $dough);

    Although I can’t quite figure out exactly how to put this in my plugin to pass the variables to it.

  12. Johnny wrote:

    I have tried to put this into function.php in the theme, but it doesn’t work.

    I keepgetting this error:
    Hello new visitor!
    Warning: Cannot modify header information – headers already sent by (output started at /home/george/public_html/lotus/wp-content/themes/split/functions.php:13) in /home/george/public_html/lotus/wp-content/themes/split/functions.php on line 4

    What am i doing wrong?

    • Ben Racicot wrote:

      Just couldn’t leave this unnatended. You gotta wrap that functionality in an if(!is_admin()) { … }

      • Devin wrote:

        Thanks Ben. Code has been updated.

  13. Always you and your posts!

    Thanks so much, I was going mad with this damned cookies. Bless COOKIEPATH and COOKIE_DOMAIN! :D

    Thanks again Davin,
    Sebastian

  14. Nikesh wrote:

    Hi this is nice article. but i want to add cookies while i load my body class any suggestion.

  15. Siegfried wrote:

    it works perfectly, thanks for sharing!

  16. I’m having a similar problem to Johnny above.

    My site uses the Required+ Foundation 4 theme, WP 3.6.1.

    I’ve added the code exactly as shown above to the bottom of my child theme’s functions.php file.

    I get the following warning:
    Warning: Cannot modify header information – headers already sent by (output started at /home/pfp/public_html/ppc/wp-content/plugins/maintenance/index.php:36) in /home/pfp/public_html/ppc/wp-content/themes/pfp/functions.php on line 143

    Ultimately, I want to track which of several background images have been shown so that I can display a new (random) image each time the page is refreshed.

    Thanks,
    David R

    • Devin wrote:

      It might be better to use javascript and local storage for something like that.

  17. Just the information that I needed about cookies thanks.

  18. David Albert wrote:

    I’ve probably referred to this post a 1/2 dozen times since it went up. Just want to say thanks for publishing this.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>