Setting Cookies in WordPress

There's the wrong way & the WordPress way to set cookies via PHP — both work, but only one follows WordPress coding standards. Learn how to utilize core constants to get & set cookies.
Published
Updated
Typical Read
5 minutes
Sponsored
Help support open-source projects & pro-bono non-profit services by donating today.
Find your next wordpress developer job
jobs by Indeed

Setting cookies in WordPress — the WordPress way, here’s how. Use the built-in core cookie constants to properly set these delicious little treats, the digital kind, of course, in any WordPress theme or plugin.

tl;dr

// Set a WordPress cookie
// setcookie( key, value, expiration, COOKIEPATH, COOKIE_DOMAIN );
setcookie( 'cookie_name', 'cookie_value', 0, COOKIEPATH, COOKIE_DOMAIN );

// Get a cookie in WordPress
// $_COOKIE[ key ];
$_COOKIE[ 'cookie_name' ];

// Delete a cookie in WordPress
unset( $_COOKIE[ 'cookie_name' ] );

Or even better, wrap it in a simple reusable function:

/**
 * Get/set a cookie in WordPress.
 *
 * This function returns a cookie value when only the $key is passed, or sets a
 * cookie when both the $key and $value are passed.
 *
 * @since x.x.x
 *
 * @param string $key The cookie name/key.
 * @param string $value Optional. The cookie value.
 * @param string|int $expiration  Optional. Timestamp when the cookie expires.
 * @return boolean|string|int The cookie value if only the $key is passed, true is successfully set a cookie, false otherwise.
 */
if ( ! function_exists( 'plugin_cookie' ) ) {
  function plugin_cookie( $key, $value = false, $expiration = false ) {
    if ( $value ) {
      // Set a cookie
      return setcookie( $key, $value, $expiration, COOKIEPATH, COOKIE_DOMAIN );
    }

    return isset( $_COOKIE[ $key ] ) ? $_COOKIE[ $key ] : false;
  }
}

// Example usage, expires in 7 days.
$expiration = current_time( 'timestamp' ) + ( DAY_IN_SECONDS * 7 ); 
plugin_cookie( 'my_cookie', 'my_value', $expiration );

// Example usage to return a cookie's value.
echo plugin_cookie( 'my_cookie' );

// and then blow it away
unset( $_COOKIE[ 'my_cookie' ] );

Articles like Setting Cookies in WordPress delivered to your inbox.

…and don’t worry, I hate spam as much as you. Expect to hear from me at most once a week.

Setting cookies in WordPress

Setting Cookies in WordPress — the right way.

It amazes me the number of WordPress themes and plugins I come across that set cookies the wrong way. Even worse, a quick Google on the subject returns a host of inaccurate or incredibly outdated articles. Though the techniques may work, it’s not how WordPress would do it.

So how do you set cookies in WordPress? With core constants:

  • COOKIEPATH — Server path in which the cookie will be available on.
  • COOKIE_DOMAIN — The (sub)domain that the cookie is available to.

Setting cookies in WordPress, especially the expiration is a cinch using one of the core time constants, available since v3.5:

  • MINUTE_IN_SECONDS = 60 seconds
  • HOUR_IN_SECONDS = 3,600 seconds
  • DAY_IN_SECONDS = 86,400 seconds
  • WEEK_IN_SECONDS = 604,800 seconds
  • MONTH_IN_SECONDS = 2,629,746 seconds
  • YEAR_IN_SECONDS = 31,556,952 seconds

Don’t forget to add the current timestamp to one of these constants, for example:

// 5 minutes into the future
$five_minutes = current_time( 'timestamp' ) + ( MINUTE_IN_SECONDS * 5 );

// 5 hours into the future
$three_hours = current_time( 'timestamp' ) + ( HOUR_IN_SECONDS * 5 );

// 5 days into the future
$five_days = current_time( 'timestamp' ) + ( DAY_IN_SECONDS * 5 );

// 5 weeks into the future
$five_weeks = current_time( 'timestamp' ) + ( WEEK_IN_SECONDS * 5 );

// 5 months into the future
$five_months = current_time( 'timestamp' ) + ( MONTH_IN_SECONDS * 5 );

// 5 years into the future
$five_years = current_time( 'timestamp' ) + ( YEAR_IN_SECONDS * 5 );

Where to set cookies in WordPress

Prior to any output. Ideally in a hook on or before get_header().

Setting cookies in WordPress is not complicated. Where to set them is key. In order for it to work, you must define them before any output on the page. This can be done in a number of hooks, but most often is done in init(). You can also set them in the following:

  • setup_theme — Fires before the theme is loaded. See the documentation.
  • after_setup_theme — Fires after the theme is loaded. See the documentation.
  • init — Fires after WordPress has finished loading but before any headers are sent. See the documentation.
  • wp_loaded — This hook is fired once WordPress, all plugins, and the theme are fully loaded and instantiated. See the documentation.

A delicious treat — can’t go wrong with a traditional chocolate chip. As for the virtual kind, in short, their small text files stored on a user’s computer and set by a website. And a majority of sites use them, one way or another.

More formally, cookies are text files stored on a device’s browser directory or program data subfolders. They’re created when a browser visits a website that uses cookies to keep track of a users’ movements, actions, etc. within that site. For the most part, they’re very useful and setting cookies in WordPress can help both the user & site in a number of ways.

For instance, cookies are used when you check that handy Remember me feature on a login form. They can help you remember where you left off, theme a site according to a user’s preferences, customize the user experience, or even help boost site performance.

It’s important to notify users that cookies are being used.

Everyday more and more privacy laws are enacted to protect users’ identity. Since cookies can store user information and be used to track habits, setting cookies in WordPress must be done in a way to comply with federal and state laws.

Recently, California passed the California Consumer Privacy Act. The CCPA allows cookies but requires the company:

  1. to provide consumers the option to opt-out of the sale of the consumer’s cookie-related data to third parties and
  2. if a third party places cookies on the company’s website, to enter into contracts that protect consumers’ information.

It’s even stricter in the European Union — in the form of the EU Directive 2009/136/EC. This is commonly referred to as the EU Cookie Law. In short, the legislation says that sites in Europe must ask visitors for their consent before installing certain types of cookies.

Cookie can impact a browsers performance.

Setting cookies in WordPress is all fine and well, just don’t get carried away. Cookies will slow down web browsers, which is why they should be cleaned regularly.

In Conclusion

Setting cookies in WordPress, properly, is a cinch once you understand and use the baked-in constants. Just make sure you use them responsibly.

Do you currently use cookies to enhance user experience? Or do you have other techniques to recommend for setting, getting and deleting cookies in WordPress? Share your experiences in the comments below.

Did you find Setting Cookies in WordPress useful? Get articles in your inbox.

…and don’t worry, I hate spam as much as you. Expect to hear from me at most once a week.

Latest Job Postings
Posted on Aug 9, 2020 at 9:17pm
Full-time
Los Angeles
Posted on Aug 9, 2020 at 9:15pm
Full-time
Los Angeles
Posted on Aug 9, 2020 at 1:19am
Littleton, CO
jobs by Indeed
Sponsored
Do you have a great article to share you want to contribute? Contact me about your idea.
Sponsored
Help support open-source projects & pro-bono non-profit services by donating today.
Sponsored
Do you run a development agency, freelance developer or offer website services. Contact me today for information about advertising.
Sponsored
Do you have a great article to share you want to contribute? Contact me about your idea.
Sponsored
Sponsor my site by donating to help support open-source projects, like WordPress Zero Spam, Referrer Analytics & others.

Leave a Reply

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

All comments posted on 'Setting Cookies in WordPress' are held for moderation and only published when on topic and not rude. Get a gold star if you actually read & follow these rules.

You may write comments in Markdown. This is the best way to post any code, inline like `<div>this</div>` or multiline blocks within triple backtick fences (```) with double new lines before and after.

Want to tell me something privately, like pointing out a typo or stuff like that? Contact Me.