Cookies in WordPress: set, read and delete them safely
A dismissed banner, a list or grid view, the last visited category: small preferences like these are often stored in a cookie. PHP’s setcookie() does the job, but in WordPress there are details to get right: when to call it, which path and domain to use, which flags to set, and the fact that page caching can make server-side cookies useless for guests.
Problem: A site should remember for 30 days that a visitor closed a welcome banner and whether they prefer the list or the grid view of the shop.
Solution: Set cookies with setcookie() and an options array (PHP 7.3+) before any output, on init or template_redirect, with COOKIEPATH and COOKIE_DOMAIN, secure on HTTPS and a samesite value. Read them from $_COOKIE and validate the value against a list of allowed values. For pages served from cache, read and set the cookie in JavaScript instead.
Setting a cookie
<?php
function ha_set_cookie( $name, $value, $days = 30, $httponly = true ) {
if ( headers_sent() ) {
return false;
}
return setcookie( $name, $value, array(
'expires' => time() + $days * DAY_IN_SECONDS,
'path' => COOKIEPATH ? COOKIEPATH : '/',
'domain' => COOKIE_DOMAIN,
'secure' => is_ssl(),
'httponly' => $httponly,
'samesite' => 'Lax',
) );
}
add_action( 'template_redirect', function () {
if ( isset( $_GET['view'] ) && in_array( $_GET['view'], array( 'list', 'grid' ), true ) ) {
ha_set_cookie( 'ha_shop_view', $_GET['view'] );
}
} );
A cookie is an HTTP header, so it must be sent before any HTML: after the theme has printed the header, setcookie() fails with “headers already sent”. template_redirect runs late enough to know which page is shown and early enough for headers.
samesite controls whether the browser sends the cookie on requests from other sites. Lax is a good default; Strict also drops the cookie when a visitor follows a link from another site to yours, which can look like the preference was forgotten.
Reading it
<?php
function ha_shop_view() {
$view = isset( $_COOKIE['ha_shop_view'] ) ? sanitize_key( wp_unslash( $_COOKIE['ha_shop_view'] ) ) : '';
return in_array( $view, array( 'list', 'grid' ), true ) ? $view : 'grid';
}
Cookie values come from the browser and can be anything. Accept only values you expect, and never use a cookie for decisions about permissions.
A cookie set in this request is not in $_COOKIE yet; it arrives with the next request. Use the value you just set directly if the current page needs it.
Deleting it
<?php setcookie( 'ha_shop_view', '', array( 'expires' => time() - HOUR_IN_SECONDS, 'path' => COOKIEPATH ? COOKIEPATH : '/', 'domain' => COOKIE_DOMAIN ) );
The path and domain must be the same as when the cookie was set, otherwise the browser keeps the old one.
Cached pages: use JavaScript
With full-page caching, guests get the same HTML whatever their cookies say, and the PHP above does not even run for cached pages. For guest preferences, set and read the cookie in the browser:
document.cookie = 'ha_banner_closed=1; max-age=' + 30 * 86400 + '; path=/; samesite=lax' + ( location.protocol === 'https:' ? '; secure' : '' );
if ( document.cookie.split( '; ' ).indexOf( 'ha_banner_closed=1' ) !== -1 ) {
document.querySelector( '.ha-banner' )?.remove();
}
Cookies that JavaScript must read cannot be httponly; that flag is for cookies only the server needs.
NOTE: Under GDPR and the ePrivacy rules, cookies that are strictly necessary or store a preference the user set themselves (closing a banner, choosing a view) usually do not need consent, while analytics and marketing cookies do. Document the cookies your plugin sets in its privacy policy text.