How to set a cookie in Wordpress

How to set a cookie in Wordpress

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Diagnosing Header Modification Errors in WordPress

When you attempt to set a cookie using setcookie() directly inside a theme's header.php file, you often encounter the dreaded "Cannot modify header information" warning. This error indicates that PHP has already begun sending output to the browser before it could process the header data. In the context of WordPress, this usually happens because some code—whether it be whitespace at the top of the file, an echo statement, or even a single BOM character in your editor—has flushed the output buffer.

The specific error message headers already sent by (output started at .../header.php:27) points to a line number where output began. Once headers are sent, you cannot technically modify them again within that request lifecycle. Consequently, the cookie does not set, and if you rely on JavaScript to read it immediately via document.cookie, it will be empty or inaccessible depending on the browser's security policies.

While moving the code to an init hook is a common suggestion found in forums, it introduces significant architectural pitfalls. The init action fires very early in the load sequence, often before the current user session is fully established or before other plugins might have injected necessary headers. More critically, if you trigger setcookie() during init, you are setting a cookie for every single page request immediately after the server starts processing it. This approach bypasses WordPress's standard header management hooks and can lead to unpredictable behavior when combined with caching plugins or security headers like HSTS.

The robust solution lies in utilizing WordPress's built-in header filters: wp_head. By hooking into this action, you ensure that your code executes specifically within the <head> tag context, after WordPress has finished generating its default headers but before the browser renders the page. This guarantees that no whitespace or unintended output has preceded your cookie logic.

Here is how to implement a persistent, cross-domain compatible cookie correctly:

add_action( 'wp_head', 'my_custom_cookie_handler' );

function my_custom_cookie_handler() {
    // Set path to '/' and domain to '' (empty string) to make it available across subdomains
    setcookie(
        'test', 
        'test_value', 
        time() + 3600, // Expires in 1 hour
        '/',             // Path
        '',              // Domain (empty for current host/subdomains)
        false,           // Secure (false for http)
        true             // HttpOnly (prevents XSS access via JS)
    );
}

Several implementation details deserve attention. The fourth parameter of setcookie() defines the path; setting it to '/' ensures the cookie is sent with requests to all paths within the domain. The fifth parameter, the domain, should remain empty ('') unless you explicitly want to scope the cookie to a specific subdomain or parent domain. Leaving it empty allows the browser to send the cookie to the current host and any subdomains (e.g., sub.example.com), which is generally safer for modern architectures.

Security is paramount when handling cookies. Always set the HttpOnly flag to true. This prevents JavaScript from accessing the cookie via document.cookie, mitigating risks associated with Cross-Site Scripting (XSS) attacks. If your site uses HTTPS, you must also set the Secure flag to true. Failing to do so on a secure connection will cause modern browsers to silently ignore the setcookie() call for security reasons.

Finally, remember that cookies are stateless and tied to the HTTP protocol. They cannot be shared between requests unless explicitly set with a domain attribute that covers multiple hosts. If you need to persist data across different subdomains (e.g., switching from a blog subdomain to a shop subdomain), ensure the domain parameter is configured correctly or explicitly set to the main domain.

For complex scenarios involving session management or cross-site tracking, consider reviewing resources on secure cookie handling. While specific platform integrations may vary, understanding the underlying HTTP mechanics ensures your implementation remains stable regardless of the CMS you are using.

Our network