Zimt

How to Set, Get, and Delete WordPress Cookies

· 5 min read · Cookies and Bars

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

To manage cookies in WordPress, you use PHP's built-in cookie functions combined with WordPress's hooks and global variables. This guide shows you how to set, retrieve, and delete cookies safely, including how to make them work with logged-in users and caching. You'll need a basic understanding of PHP and access to your theme's functions.php file or a custom plugin.

What You'll Need

  • A WordPress site with FTP or file manager access (to edit theme files or create a plugin).
  • Basic knowledge of PHP syntax.
  • A code editor (like VS Code or Notepad++) to avoid syntax errors.

Step-by-Step

  1. Set a cookie in WordPress
    Use the PHP setcookie() function inside a WordPress hook that runs before headers are sent. The best hook is init or wp_loaded. Add this code to your theme's functions.php or a custom plugin:
    add_action('init', 'my_set_cookie');
    function my_set_cookie() {
      if (!isset($_COOKIE['my_cookie'])) {
        setcookie('my_cookie', 'hello', time() + 3600, COOKIEPATH, COOKIE_DOMAIN);
      }
    }

    Replace my_cookie with your cookie name, 'hello' with the value, and 3600 with the expiration time in seconds (1 hour). Use COOKIEPATH and COOKIE_DOMAIN to match WordPress's default cookie paths.
  2. Get a cookie value
    To read the cookie, use the global $_COOKIE array. For example:
    $my_value = isset($_COOKIE['my_cookie']) ? sanitize_text_field($_COOKIE['my_cookie']) : '';
    Always sanitize the value before using it in your theme or outputting it.
  3. Delete a cookie
    To delete a cookie, set its expiration time to a past timestamp. Use the same path and domain as when setting it:
    setcookie('my_cookie', '', time() - 3600, COOKIEPATH, COOKIE_DOMAIN);
    This removes the cookie from the user's browser. Note: you must call this before any output is sent to the browser.
  4. Make cookies available to admin-ajax
    If you need to use cookies in AJAX requests, pass the cookie value via a localized script or a hidden field, because $_COOKIE might not be available in the AJAX handler depending on how the request is made. For example, use wp_localize_script() to pass the value to your JavaScript.
  5. Set cookies for logged-in users only
    To set a cookie only when a user is logged in, wrap your code in if (is_user_logged_in()). This prevents setting cookies for anonymous visitors, which can help with caching performance.
  6. Test your cookies
    After adding the code, clear your browser cache and cookies, then load your site. Use your browser's developer tools (F12) > Application > Cookies to verify that the cookie is set, has the correct value, and expires as expected.

Common Mistakes

  • Headers already sent: Calling setcookie() after any HTML output (including whitespace or BOM) causes a warning and the cookie won't be set. Always hook into init or earlier.
  • Wrong path or domain: If you set a cookie with a different path than the one used to retrieve it, it won't be accessible. Use COOKIEPATH and COOKIE_DOMAIN to stay consistent.
  • Not sanitizing values: Outputting cookie values directly without sanitization can lead to XSS vulnerabilities. Always use sanitize_text_field() or similar.
  • Forgetting to delete with same parameters: To delete a cookie, you must use the same name, path, and domain as when you set it. Otherwise, the cookie remains.

Tips

  • Use a unique prefix for your cookie names (e.g., myplugin_) to avoid conflicts with other plugins.
  • For persistent cookies, set a longer expiration (e.g., 30 days = 2592000 seconds), but be mindful of user privacy and GDPR compliance.
  • If you're using a caching plugin, test your cookie behavior with caching enabled. Some caching plugins might strip or ignore cookies for anonymous users.
  • Consider using WordPress's wp_parse_args() to merge default cookie settings if you have multiple cookies.

Troubleshooting

  • Cookie not being set: Check for any output before setcookie(). Look for extra spaces or BOM in your functions.php file. Also verify that the hook is firing by adding a temporary error_log.
  • Cookie not available in AJAX: Remember that AJAX requests might not include cookies unless you pass them explicitly. Use wp_localize_script() to pass the value to JavaScript, or set the cookie via JavaScript using document.cookie.
  • Cookie disappears after page reload: Ensure the expiration time is in the future and that you're using the correct path. Also check if your browser blocks third-party cookies.
  • Headers already sent warning: Move your setcookie() call to an early hook like init or plugins_loaded. Also check your theme's functions.php for stray whitespace before the opening <?php tag.

Frequently Asked Questions

Can I set cookies in WordPress without PHP?

Yes, you can use JavaScript to set cookies with document.cookie, but PHP is more reliable for server-side logic and security. JavaScript cookies are visible to the client and can be manipulated.

How do I make a cookie accessible across subdomains?

Set the domain parameter to your root domain (e.g., .example.com) when calling setcookie(). In WordPress, you can use COOKIE_DOMAIN if it's defined, or set it manually.

Is it safe to store user data in cookies?

Cookies are stored on the client side and can be read or modified by users. Never store sensitive data like passwords or credit card numbers. Store a unique identifier and look up the data on the server.

How do I delete a cookie for all users?

You cannot delete a cookie on the server for all users. You can only set a past expiration time when a user visits your site. To force a deletion, you might need to run a script that sets the cookie for each visitor.

Do cookies work with WordPress REST API?

Yes, but you need to handle nonces and authentication. For public REST requests, cookies are sent automatically if the domain matches. For authenticated requests, you need to include a nonce in the request header.

Can I use cookies with page caching?

Yes, but caching plugins often skip serving cached pages for users with certain cookies. You can configure your caching plugin to exclude pages when a specific cookie is present, or use a plugin that supports dynamic cookies.