How to Set, Get, and Delete WordPress Cookies (Like a Pro)

Understanding WordPress Cookies
Cookies are small text files that websites store on a user’s computer to remember information about them. Think of them as digital breadcrumbs left behind as users navigate a site. In the context of WordPress, cookies are used for various purposes, including:
- Authentication: Remembering logged-in users so they don’t have to re-enter credentials on every page.
- Personalization: Tailoring the user experience based on preferences, like language or theme settings.
- Tracking: Monitoring user behavior for analytics, advertising, and retargeting purposes.
- Shopping Carts: Storing items added to a cart in an e-commerce store.
WordPress uses several default cookies, notably:
- `wordpress_[hash]`: Contains your authentication details (username, password hash) and is used to log you in.
- `wordpress_logged_in_[hash]`: Indicates when you’re logged in and who you are.
- `wp-settings-[UID]` & `wp-settings-time-[UID]`: Customize your interface in the wp-admin area. UID refers to your user ID.
While WordPress manages some cookies automatically, developers often need to set, retrieve, and delete custom cookies for enhanced functionality or specific plugin requirements.
Setting Cookies in WordPress
The primary function for setting cookies in WordPress is `setcookie()`. This function is a standard PHP function, but WordPress also provides a wrapper function, `wp_setcookie()`, which offers some additional benefits and ensures consistency within the WordPress environment.
Using the `setcookie()` Function
The basic syntax of `setcookie()` is as follows:
“`php
setcookie( string $name, string $value = “”, int $expires = 0, string $path = “”, string $domain = “”, bool $secure = false, bool $httponly = false ): bool
“`
Let’s break down each parameter:
- `$name`: The name of the cookie. This is how you’ll identify the cookie when retrieving it.
- `$value`: The value to be stored in the cookie. This can be a string, number, or even a serialized array.
- `$expires`: The timestamp (in seconds since the Unix epoch) when the cookie expires. If set to 0, the cookie expires when the browser is closed (session cookie).
- `$path`: The server path where the cookie is valid. Setting this to `/` makes the cookie available across the entire domain.
- `$domain`: The domain for which the cookie is valid. To make it valid for the current domain, you can leave it blank or use `.example.com` (replace `example.com` with your actual domain).
- `$secure`: Indicates whether the cookie should only be transmitted over HTTPS. Set to `true` for secure cookies.
- `$httponly`: When `true`, the cookie will be accessible only through the HTTP protocol. This helps mitigate cross-site scripting (XSS) attacks by preventing JavaScript access.
Example:
“`php
setcookie( ‘my_custom_cookie’, ‘Hello, World!’, time() + (86400 * 30), ‘/’, ”, true, true ); // Expires in 30 days, secure, HTTP only
“`
This code sets a cookie named ‘my_custom_cookie’ with the value ‘Hello, World!’, expiring in 30 days, accessible across the entire domain, and only transmitted over HTTPS, with HTTP only protection.
Using the `wp_setcookie()` Function
The `wp_setcookie()` function provides a more WordPress-friendly way to set cookies. Its syntax is:
“`php
wp_setcookie( string $name, string $value = ”, int $expire = 0, string $path = ”, string $domain = ”, bool $secure = false, bool $httponly = false ): bool
“`
The parameters are identical to `setcookie()`, but `wp_setcookie()` handles some WordPress-specific configurations internally. It’s generally recommended to use `wp_setcookie()` within WordPress themes and plugins.
Example:
“`php
wp_setcookie( ‘my_custom_cookie’, ‘Hello, WordPress!’, time() + (86400 * 30), ‘/’, ”, true, true ); // Expires in 30 days, secure, HTTP only
“`
This code achieves the same result as the `setcookie()` example but uses the WordPress wrapper function.
Important Considerations When Setting Cookies
- Timing: Cookies must be set *before* any output is sent to the browser (including HTML). This is because cookies are sent as part of the HTTP headers. Attempting to set a cookie after output has started will result in a PHP warning: “Cannot modify header information – headers already sent.” The `plugins_loaded` action hook is a good place to set cookies as it fires early in the WordPress loading sequence.
- Security: Always sanitize data before storing it in a cookie. Use `esc_attr()` or similar functions to prevent malicious code from being injected.
- Expiration: Consider setting appropriate expiration times for cookies. Avoid unnecessarily long expiration periods.
- HTTPS: If your site uses HTTPS (and it should!), set the `secure` flag to `true` for sensitive information to ensure the cookie is only transmitted over secure connections.
- HTTP Only: Setting the `httponly` flag to `true` helps prevent cross-site scripting (XSS) attacks by making the cookie inaccessible to JavaScript.
- Path and Domain: Set the `path` and `domain` parameters carefully to control where the cookie is valid.
Example: Setting a Cookie on Theme Activation
Here’s an example of how to set a cookie when a WordPress theme is activated:
“`php
function my_theme_activation_cookie() {
wp_setcookie( ‘my_theme_activated’, ‘true’, time() + (60 * 60 * 24), COOKIEPATH, COOKIE_DOMAIN ); // Expires in 1 day
}
add_action( ‘after_switch_theme’, ‘my_theme_activation_cookie’ );
“`
This code sets a cookie named `my_theme_activated` when the theme is activated. The `COOKIEPATH` and `COOKIE_DOMAIN` constants are predefined in WordPress and represent the default path and domain for cookies. This is a useful way to perform actions immediately after theme activation.
Getting Cookies in WordPress
Accessing cookies in WordPress is straightforward using the `$_COOKIE` superglobal array. This array contains all the cookies sent by the user’s browser to the server.
Accessing Cookie Values
To retrieve the value of a cookie, simply use its name as the key in the `$_COOKIE` array:
“`php
$my_cookie_value = $_COOKIE[‘my_custom_cookie’];
if ( isset( $my_cookie_value ) ) {
echo ‘The value of my_custom_cookie is: ‘ . esc_html( $my_cookie_value ); // Sanitize output!
} else {
echo ‘my_custom_cookie is not set.’;
}
“`
It’s crucial to use `isset()` to check if the cookie exists before attempting to access its value. This prevents PHP warnings if the cookie is not present. Also, remember to sanitize the output of the cookie value using `esc_html()` or a similar function to prevent XSS vulnerabilities.
Example: Displaying a Message Based on a Cookie
Here’s an example of how to display a different message to the user based on the value of a cookie:
“`php
function display_cookie_message() {
if ( isset( $_COOKIE[‘my_theme_activated’] ) && $_COOKIE[‘my_theme_activated’] === ‘true’ ) {
echo ‘
‘;
} else {
echo ‘
‘;
}
}
add_action( ‘wp_footer’, ‘display_cookie_message’ );
“`
This code checks if the `my_theme_activated` cookie is set and its value is ‘true’. If it is, a “Thank you” message is displayed; otherwise, a generic welcome message is shown. The message is displayed in the website’s footer using the `wp_footer` action hook.
Security Considerations When Getting Cookies
- Validation: Never trust cookie data implicitly. Validate the data retrieved from cookies to ensure it’s in the expected format and within acceptable limits.
- Sanitization: Always sanitize the output of cookie values to prevent XSS vulnerabilities. Use `esc_html()`, `esc_attr()`, or other appropriate sanitization functions.
- Avoid Storing Sensitive Information: Avoid storing sensitive information (like passwords or credit card details) directly in cookies. If you must store sensitive data, encrypt it securely.
Deleting Cookies in WordPress
Deleting a cookie involves setting its expiration time to a past date. This tells the browser to remove the cookie.
Using `setcookie()` to Delete a Cookie
To delete a cookie using `setcookie()`, set its expiration time to a time in the past:
“`php
setcookie( ‘my_custom_cookie’, ”, time() – 3600, ‘/’, ”, true, true ); // Expire 1 hour ago
“`
This code sets the `my_custom_cookie` to an empty value and sets its expiration time to one hour in the past. The browser will then remove the cookie. Crucially, all other parameters (path, domain, secure, httponly) *must* match the values used when the cookie was originally set. If they don’t match, the browser won’t recognize the cookie for deletion.
Using `wp_setcookie()` to Delete a Cookie
Similarly, you can use `wp_setcookie()` to delete a cookie:
“`php
wp_setcookie( ‘my_custom_cookie’, ”, time() – 3600, ‘/’, ”, true, true ); // Expire 1 hour ago
“`
Again, the key is to set the expiration time to a past date and ensure all other parameters match the original cookie settings.
Example: Deleting a Cookie on Theme Deactivation
Here’s an example of how to delete the `my_theme_activated` cookie when a theme is deactivated:
“`php
function my_theme_deactivation_cookie() {
wp_setcookie( ‘my_theme_activated’, ”, time() – 3600, COOKIEPATH, COOKIE_DOMAIN ); // Expire 1 hour ago
}
add_action( ‘switch_theme’, ‘my_theme_deactivation_cookie’ );
“`
This code uses the `switch_theme` action hook (which fires before the new theme is activated but after the current theme has effectively been deactivated) to delete the cookie. This ensures that the cookie is removed when a new theme is activated.
Important Considerations When Deleting Cookies
- Matching Parameters: When deleting a cookie, you *must* use the same `path`, `domain`, `secure`, and `httponly` parameters that were used when the cookie was originally set. If these parameters don’t match, the browser will not recognize the cookie for deletion.
- Timing: Ensure that you delete the cookie at the appropriate time, such as when a user logs out, a setting is changed, or a theme is deactivated.
Best Practices for Working with WordPress Cookies
- Use `wp_setcookie()`: Prefer `wp_setcookie()` over `setcookie()` for better WordPress compatibility and consistency.
- Sanitize Data: Always sanitize data before storing it in a cookie and sanitize the output of cookie values to prevent XSS vulnerabilities.
- Validate Data: Validate data retrieved from cookies to ensure it’s in the expected format and within acceptable limits.
- Set Appropriate Expiration Times: Consider setting appropriate expiration times for cookies. Avoid unnecessarily long expiration periods.
- Use HTTPS: If your site uses HTTPS, set the `secure` flag to `true` for sensitive information.
- Use HTTP Only: Set the `httponly` flag to `true` to help prevent cross-site scripting (XSS) attacks.
- Avoid Storing Sensitive Information: Avoid storing sensitive information directly in cookies. If you must, encrypt it securely.
- Document Your Cookies: Keep a record of the cookies your theme or plugin sets, their purpose, expiration times, and other relevant details. This helps with maintainability and debugging.
By following these guidelines, you can effectively set, get, and delete WordPress cookies while maintaining security and best practices. Remember to thoroughly test your code and consider the potential impact on user privacy when working with cookies.
- How to Completely Customize Your WordPress RSS Feeds
- WordPress Playground – How to Use WordPress in Your Browser
- How to Create a Custom Calculator in WordPress (Step by Step)
- How to Easily Create a Staging Site for WordPress (Step by Step)
- How to Save Contact Form Data in the WordPress Database
- How to Easily Do Visual Regression Testing in WordPress
- How to Create Advanced Search Form in WordPress for Custom Post Types