Key Takeaways
WordPress relies on browser-side cookies to store user credentials and site preferences, enabling highly personalized digital experiences. This decentralized storage model keeps user data safe in individual browsers even if the central website experience is temporarily compromised.
By default, WordPress generates session cookies to keep users logged in and comment cookies to remember personal details for future interactions. Understanding these out-of-the-box functions helps administrators manage user engagement and plan for global privacy compliance requirements.
Developers can easily set, retrieve, and delete custom WordPress cookies by adding PHP code directly to the active themeās functions.php file. Properly configuring parameters like expiration limits and secure transfer protocols is essential for maintaining site performance and security.
To optimize user trust and ensure regulatory compliance, website administrators should audit their active plugins for cookie usage and display transparent consent notices. Reviewing these data practices is a critical step in providing a modern, privacy-first digital experience.
Youāve probably noticed that a lot of the websites you visit ārememberā things about you. The information they store can be anything from your login credentials to items youāve browsed, articles youāve liked, and more.
To do that, websites use what are called ācookies.ā Cookies on the web enable sites to store key information safely within visitorsā browsers. That way, they can provide a more personalized experience without putting user data at risk.
In this article, weāll break down how cookies work and the ways WordPress in particular uses them. Then weāll teach you how to set up custom cookies in WordPress. Letās get to work!
What are cookies in WordPress?
Simply put, cookies are files that your website stores in visitorsā browsers, which contain information about them. Here are some common examples of cookie use throughout the web:
- Storing session information that has been authenticated using login credentials, so users donāt have to re-enter them each time they visit your site.
- Remembering specific pages that visitors have been looking at lately (i.e., āRecent productsā on eCommerce sites).
- Noting specific user behavior, such as when they last visited your site.
Cookies are everywhere on the web, to the extent that thereās even specific legislation that governs how you can use them in some parts of the world.
Overall, browsing the web would be a slower and less personal experience without cookies. Websites wouldnāt be able to remember any of the information that makes your life easier. Thatās why WordPress is set up to use cookies out of the box.
How WordPress uses cookies
By default, WordPress generates two types of cookies unless you tell it to do otherwise. Those include:
- Session cookies: These are the ones that tell your browser: āHey, we just logged into this site a little while ago, letās reuse that session.ā That saves you from logging in over and over on the same sites.
- Comments cookies: Whenever you comment on a WordPress website, it will save some of your details so you donāt have to re-enter them later on. That can include your username, email address, and more.
How WordPress plugins use cookies
As you might imagine, WordPress plugins and other third-party tools also make extensive use of cookies. For example, if you use a related posts plugin, it probably takes advantage of cookies to store information about which pages users have viewed.
Likewise, analytics plugins tend to use cookies to store user behavior data. In most cases, these cookies are harmless. However, these days you might need to display a cookie notice on your website, depending on where you do business.
Youāve probably seen these cookie notices all around the web, and itās no coincidence. People are more interested than ever in online privacy, so it only makes sense that many websites try to be as transparent as possible.
How to set cookies in WordPress
Youāll need to use PHP to create and set up cookies in WordPress. Where you add the necessary code depends on whether you want to use your theme or a custom plugin. Letās take a look at how the first method works.
Step 1: Open your themeās functions.php file
In most cases, the theme approach is the easiest route to take. To set a new cookie, youāll want to edit your active themeās functions.php file.
We should note that any changes you make to your theme should likely be done in a child theme. This ensures they wonāt be wiped out when the parent theme is updated.
Open your active themeās folder, and look for the functions.php file inside. To add a custom cookie, youāll need to include some additional code within this file. Before that, however, you need to understand what parameters you can use:
- The name of the cookie
- Its value
- How long until it expires (it canāt last forever!)
- Which pages the cookie will act on
- Your domain and/or subdomains
- Whether it should transfer over HTTP or HTTPS
Weāre going to use these parameters within the next section, so donāt worry if you donāt fully understand what each of them does just yet.
Step 2: Add your new cookieās code
Once you open the functions.php file, youāll be able to add custom code to it. Hereās an example of the code youād use to add a new cookie:eās an example of the code youād use to add a new cookie:
/**
* Shared cookie settings.
* Keeping these in one place helps ensure create/delete use the same path/domain/etc.
*/
function wpdocs_visit_cookie_options() {
return array(
// If WordPress defines a cookie path, use it; otherwise fall back to root.
'path' => ( defined( 'COOKIEPATH' ) && COOKIEPATH ) ? COOKIEPATH : '/',
// Empty domain means "current host" behavior in most cases.
'domain' => defined( 'COOKIE_DOMAIN' ) ? COOKIE_DOMAIN : '',
// Only send cookie over HTTPS when site is on SSL.
'secure' => is_ssl(),
// Prevent JavaScript from reading this cookie (mitigates some XSS impact).
'httponly' => true,
// Good default for normal site navigation and basic CSRF protection.
'samesite' => 'Lax',
);
}
/**
* CREATE: set visit_time once, storing a Unix timestamp.
*/
function wpdocs_set_visit_time_cookie() {
// Cookies are sent in headers; bail if headers already went out.
if ( headers_sent() ) {
return;
}
// Only set on first visit (or until cookie expires).
if ( isset( $_COOKIE['visit_time'] ) ) {
return;
}
// Store Unix timestamp as a string.
$value = (string) time();
// Expire in 24 hours.
$expires = time() + DAY_IN_SECONDS;
$opts = wpdocs_visit_cookie_options();
setcookie(
'visit_time',
$value,
array(
'expires' => $expires,
'path' => $opts['path'],
'domain' => $opts['domain'],
'secure' => $opts['secure'],
'httponly' => $opts['httponly'],
'samesite' => $opts['samesite'],
)
);
// Keep current request state in sync (browser receives cookie on next request).
$_COOKIE['visit_time'] = $value;
}
// Run early so cookie headers are set before output.
add_action( 'init', 'wpdocs_set_visit_time_cookie', 1 );
That code includes the parameters we laid out in the last section. Thereās the cookie name (cookies_timestamp), its value (visit_time), and how long until it expires. For additional information on configuring your cookie, see the PHP docs on setcookie.
This cookie generates a timestamp of the last time someone visited your site. You might then use the cookie to display a message such as, āYour last visit was on January 25th, 2019.ā This lets users know if someone else has accessed their account.
As for the expiration time, youāll notice itās in seconds. We set the value for a day, which is pretty short by cookie standards. The rest of the parameters donāt matter as much, because the default options work well enough in almost every case.
When youāre done configuring your cookie, save the changes to functions.php. Once you deploy this code to your site using your regular methods, your cookie will start working right away!
How to get a cookie and use it in WordPress
In the last section, we talked about how you can use cookies in web development to store relevant user-specific data. Thereās a specific function you can use to āgetā cookies, so to speak.
To use it, youāll need to edit your themeās functions.php file once more. Hereās a quick example:
/**
* READ: return a formatted label from the visit_time timestamp.
* Returns empty string when cookie is missing/invalid.
*/
function wpdocs_get_visit_time_label() {
// No cookie yet means first visit.
if ( empty( $_COOKIE['visit_time'] ) ) {
return '';
}
// Unslash + cast to safe positive integer.
$timestamp = absint( wp_unslash( $_COOKIE['visit_time'] ) );
if ( ! $timestamp ) {
return '';
}
// Format using WordPress date handling (timezone-aware).
return wp_date( 'F j, Y g:i a', $timestamp );
}
/**
* Use the formatted date in your php as needed in a template file, theme action hook, shortcode, or block render callback.
*/
$last_visit = wpdocs_get_visit_time_label();
if ( $last_visit ) {
echo '<p class="visit-time"><strong>Welcome back!</strong> Your last visit was on: ' . esc_html( $last_visit ) . '</p>';
}
In a nutshell, this creates a second function that checks to see if the visit_time cookie we created during the last section is there. If it is, then the code will return a formatted date for use in our theme.
Deleting a Cookie in WordPress
To delete a cookie, you canāt just clear it with PHP memory functions. You have to tell the visitorās browser that the cookie has expired. You can achieve this by setting its expiration date to a time in the past.
To delete a cookie safely in WordPress, add the following code to your themeās functions.php file:
/**
* DELETE: expire in the past using matching attributes.
*/
function wpdocs_delete_visit_time_cookie() {
// Need headers + existing cookie to attempt deletion.
if ( headers_sent() || ! isset( $_COOKIE['visit_time'] ) ) {
return;
}
$opts = wpdocs_visit_cookie_options();
setcookie(
'visit_time',
'',
array(
// Past timestamp tells browser to remove cookie.
'expires' => time() - HOUR_IN_SECONDS,
'path' => $opts['path'],
'domain' => $opts['domain'],
'secure' => $opts['secure'],
'httponly' => $opts['httponly'],
'samesite' => $opts['samesite'],
)
);
unset( $_COOKIE['visit_time'] );
}
// Example hook:
// add_action( 'wp_logout', 'wpdocs_delete_visit_time_cookie' );
AAs always, remember that weāre using placeholders in our example. Youāll want to modify that code depending on your specific cookieās name. Once the browser processes this script, the cookie will be permanently removed from the userās system.
Conclusion
Cookies are one of the many ways modern websites can provide their users with a better experience. Using WordPress, you can configure cookies to personalize your site for each visitor.
If you want to learn about other techniques for improving the user experience, check out our developer resources, where you can find dozens of guides and tutorials. While youāre at it, improve your experience with a host specifically optimized for WordPress. Take a look at our plansāchances are youāll find a great fit!