How can I set, get and destroy cookies in WordPress?

How can I set, get and destroy cookies in WordPress?

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

Stefan Bogdanescu

Founder & Senior Architect

Managing Cookies in WordPress: A Developer's Guide

WordPress provides a robust set of functions to handle HTTP cookies, abstracting away the raw $_COOKIE superglobal and setcookie() calls while maintaining compatibility with PHP standards. To effectively manage session data, you need to understand when these functions execute within the request lifecycle. The critical constraint is that cookie operations must occur before any HTML output is sent to the browser; otherwise, you will encounter a "Cannot modify header information" error.

Setting Cookies

The primary function for creating cookies is setcookie(). In WordPress, this is often wrapped to ensure headers are modified correctly even if content has already been partially buffered, though strictly speaking, it must be called before any echo statements in your theme or plugin files.

/**
 * Sets a standard PHP cookie.
 *
 * @param string $name The cookie name.
 * @param string $value The cookie value.
 * @param int $expire Expiration timestamp (0 = session).
 * @param string $path Cookie path.
 * @param bool $secure Use HTTPS only?
 * @param bool $httponly Restrict to HTTP only?
 */
function my_custom_cookie( $name, $value, $expire = 0, $path = '/', $secure = false, $httponly = true ) {
    setcookie(
        $name, 
        $value, 
        [
            'expires' => $expire,
            'path'    => $path,
            'secure'  => $secure,
            'httponly'=> $httponly,
        ]
    );
}

// Usage: Set a cookie that expires in 24 hours and is secure.
my_custom_cookie( 'user_preference', 'dark_mode', time() + 86400, '/', true, true );

When implementing this in a WordPress plugin, ensure the function runs within appropriate hooks like wp_loaded or inside an AJAX handler to avoid conflicts with theme output. Always validate inputs before passing them to setcookie() to prevent issues with special characters that might break the header format.

Retrieving Cookies

WordPress exposes cookies directly via the global $_COOKIE array. This is a standard PHP feature where keys are always lowercase, regardless of how they were set in JavaScript or server configuration. Accessing them looks like this:

$pref = isset( $_COOKIE['user_preference'] ) ? $_COOKIE['user_preference'] : 'light_mode';

// Always sanitize when using cookie data in your application logic.
$safe_pref = sanitize_text_field( $pref );

A common pitfall is assuming $_COOKIE contains the value immediately upon page load if the cookie was just set via an AJAX call or a previous request. In modern browsers, cookies sent to scripts are often asynchronous unless explicitly handled. If you need the cookie data to influence the current response immediately, ensure the setting happened in a prior request cycle or handle it within the same request after output buffering is managed correctly.

Destroying Cookies

To clear a cookie, you cannot simply unset the array element or set an empty value without specific parameters. You must call setcookie() again with the exact same name, path, domain, and secure attributes used when setting it, but with an expiration date in the past (e.g., -time()).

function destroy_cookie( $name ) {
    if ( isset( $_COOKIE[ $name ] ) ) { // Check existence first to ensure headers are modifiable
        setcookie( 
            $name, 
            '', 
            [
                'expires' => time() - 3600,
                'path'    => '/',
                'secure'  => true,
                'httponly'=> true,
            ]
        );
    }
}

// Usage: Clear the preference cookie.
destroy_cookie( 'user_preference' );

Failing to match the original path or secure flag will result in a new cookie being set rather than destroying the old one. This nuance is frequently overlooked when implementing logout functionality, leading to persistent login sessions despite clearing $_SESSION data.

Trade-offs and Security Considerations

The decision to use HTTP-only cookies (httponly = true) is non-negotiable for sensitive data like session tokens or authentication flags. JavaScript cannot read these cookies, which mitigates Cross-Site Scripting (XSS) attacks that attempt to steal user sessions. However, this means you cannot access the value via document.cookie if needed for client-side logic without using a separate secure token strategy.

Additionally, WordPress uses its own session management system ($_SESSION). While cookies are essential for maintaining state, relying solely on them without server-side validation can lead to CSRF vulnerabilities if forms lack proper nonce verification. Always combine cookie-based authentication with form nonces or site-wide CSRF tokens when handling state-changing operations.

Our network