Setting Cookies in WordPress

Written by
Typical Read
5 minutes

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.

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.


// 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' ] );
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.

Join the conversation.

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.