How to set, get, and delete cookies in WordPress

Cookies are small pieces of data that make your web experience smoother and more personalized. Websites rely on these cookies for essential functions like remembering your login details for future visits and facilitating user interactions, such as comments. They also help track user behavior or store preferences for a more customized experience. This is how websites seem to remember you, saving you the trouble of logging in every time or keeping your site tailored to your preferences.

However, with the introduction of the EU Cookie Law under GDPR, the ethical and legal aspects of cookie usage have become pivotal. Website owners are now required to obtain explicit consent from visitors to store and retrieve information using cookies, placing user privacy at the forefront of digital interactions.

Understanding how to manage WordPress cookies—setting, retrieving, and deleting them securely—is crucial for website administrators and developers. It’s about striking a balance between enhancing user experience and ensuring privacy and website security. Managing cookies responsibly is essential in building trust and ensuring compliance in our increasingly digital world.

TL;DR: WordPress sites use cookies to remember who you are, your login details, preferences, and site interactions. Whether you’re a site owner or a visitor, understanding how to manage cookies—from setting them up and accessing their data to securely deleting them—is key to a balanced web experience that respects user privacy while keeping things user-friendly.

Does WordPress use cookies?

Yes, WordPress sites do indeed use cookies. These small files play a significant role in enhancing your browsing experience. How do they do this? By remembering information about you, the visitor. 

For example, cookies save your login details securely, so you don’t have to log in every time you visit a site. They also keep track of your user preferences, allowing the site to adjust its layout (think light or dark modes) and functionality (think ‘Yes’ to additional cookies, or not) to suit your needs better.

But it’s not just WordPress itself that uses cookies. Third-party cookies are also common on WordPress sites, coming from plugins you might be familiar with, such as Google Analytics, Google Tag Manager, or Microsoft Clarity. These cookies are quite insightful. They store information about the pages you’ve visited and gather data on your behavior across the site. This information is invaluable for website owners, helping them understand user interaction and improve the website’s performance based on actual user data.

What Cookies does WordPress use?

WordPress utilizes cookies to enhance user experience and functionality, classifying them mainly under two categories: Session (User) and Comment cookies.

Session cookies

These WordPress cookies are deemed strictly necessary for the operation of WordPress sites, which means they cannot be turned off or opted out of. They primarily serve to store user information for a duration after logging in, and expire when the user logs off or closes their browser. However, when you select ‘Remember me’ while logging in, a session cookie remembers your login details for 15 days.

Now a session cookie has four main components, which are:

wordpress_[hash]: Stores your login details to redirect you to the admin dashboard automatically.

wordpress_logged_in_[hash]: Indicates that you’re logged in and outlines your permissions. The [hash] is a secured version of your password, created to protect your information.

wordpress-settings-{time}-[UID]: Records the time of login with your unique identifier (UID) if available.

wordpress_test_cookie: Checks if your browser supports cookies.

Additionally, WordPress sets security keys in the background to manage logged-in sessions securely, though these remain hidden from the user.

Comment cookies

Unlike session cookies, comment cookies are not strictly necessary and can be opted out of. These cookies remember user details (not login credentials) such as the user’s name, email address, and website when leaving a comment. The cookies set are:

comment_author_[hash]: Remembers the user’s name.

comment_author_email_[hash]: Stores the user’s email address.

comment_author_url_[hash]: Keeps the user’s website information.

These cookies have a lifespan of 347 days and are renewed every time the user logs in or comments, thereby resetting their expiry dates.

Under the GDPR, the EU’s Cookie Law mandates that website owners must inform visitors about the use of cookies. If a website sets cookies on a visitor’s browser, it’s legally required to notify visitors about it. This law ensures transparency and gives users a choice regarding their personal data.

How to Set cookies in WordPress

Setting WordPress cookies can enhance user experience by remembering user preferences, login statuses, or other vital information. For example, a website admin might want to set cookies that remember visitors’ language selection, so that they can be automatically redirected to that language version of their website the next time they visit. All of this, and more, can be done within the functions.php file of your theme.

To set a cookie in WordPress, you utilize the in-built PHP function called setcookie(). The steps to do that are as follows:

Step 1: Obtain your site’s FTP credentials (host IP address, username, password, and port number, if applicable) and use a client like Filezilla to access your site.

Step 2: Navigate to the directory of your site’s current theme. Usually it is in the location: /public_html/wp-content/themes/theme_name. Create a child theme out of it for safety and update reasons. Locate the functions.php file for the child theme, right-click on it, and click on View/Edit. This opens the file in your preferred file editor application.

Step 3: At the end of the file, add the setcookie() function. Here is the syntax for it:

setcookie(name, value, expire, path, domain, secure, httponly);

In this syntax:

name (compulsory): The name of the cookie you’re setting.

value: The value that the cookie is meant to store.

expire: The time the cookie is set to expire, in seconds. For example, for a cookie to last 7 days, you multiply the number of days by the number of seconds in a day (`7 * 86400`).

path: The path on your website where the cookie will be available. Usually, this is set to “/”, which means it’s available across the entire website.

domain: This can be used to specify any domains or subdomains the cookie should work for.

secure: This parameter is used to specify if the cookie should be served over HTTP or HTTPS only.

httponly: When set to true, it makes the cookie accessible only over HTTP, effectively preventing it from being accessed through scripting languages for added security.

Here is a sample code in PHP:

setcookie(“user_login”, “username123”, time() + (7 * 86400), “/”);

This creates a cookie named user_login with the value username123 that expires in 7 days and is available across the entire website.

Step 4: Save the file and close the file editor window. This brings up a pop-up that asks whether you wish to upload the edited file to the server. Click on Yes and you are done. You can now return to your site’s wp-admin dashboard and apply the child theme to activate your cookie/s.

Note: You can also use JavaScript to set a cookie. However, you’ll need to define your own function to set cookies, as JavaScript does not have an in-built function similar to setcookie() in PHP. To replicate it, edit the functions.php file as shown above and create a function to accept three parameters: the cookie’s name, its value, and its expiration date. Here is the syntax to do that:

function setCookie(cookieName, cookieValue, cookieExpiry) {
    const d = new Date();
    d.setTime(d.getTime() + (cookieExpiry*24*60*60*1000));
    let expires = “expires=”+ d.toUTCString();
    document.cookie = cookieName + “=” + cookieValue + “;” + expires + “;path=/”;
}

This function allows you to create a cookie by specifying its name, value, and the number of days before it expires.

Here is a sample code in JavaScript that uses the setCookie() function declared above:

setCookie(“user_theme”, “dark_mode”, 7);

This would create a cookie named user_theme with the value dark_mode that expires in 7 days. Save and re-upload the file to your site and you are done.

How to Get cookies in WordPress

Retrieving WordPress cookies is as straightforward as setting them, allowing you to access the stored data for various purposes such as customizing user experience or validating user sessions.

In PHP, cookies can be accessed using the $_COOKIE variable. This variable holds all the cookies that are associated with the current domain. The syntax to access a cookie is:

$value = $_COOKIE[‘cookie_name’];

where cookie_name is the name of the cookie you want to access. Keep in mind that you should check if the cookie exists before trying to use it to avoid potential errors.

Here are the steps to do that:

Step 1: Obtain your site’s FTP credentials (host IP address, username, password, and port number, if applicable) and use a client like Filezilla to access your site.

Step 2: Navigate to the directory of your site’s current theme. Usually it is in the location: /public_html/wp-content/themes/theme_name. Create a child theme out of it for safety and update reasons. Locate the functions.php file for the child theme, right-click on it, and click on View/Edit. This opens the file in your preferred file editor application.

Step 3: At the end of the file, add the following code:

if(isset($_COOKIE[‘cookie_name’])) {
    $userCookie = $_COOKIE[‘cookie_name’];
    // Perform actions with the $userCookie value
} else {
    echo “Cookie is not set!”;
}

This example checks if the cookie_name cookie is set and then retrieves its value into the $userCookie variable. It also checks if the cookie exists, and shows a message if it does not.

Step 4: Save the file and close the file editor window. This brings up a pop-up that asks whether you wish to upload the edited file to the server. Click on Yes and you are done. You can now return to your site’s wp-admin dashboard and apply the child theme to obtain your cookie/s data.

Note: Like earlier, you can also use JavaScript to access cookies. For this, you have to use the document.cookie property, which holds all the cookies as a semicolon-separated string. However, it doesn’t offer a straightforward mechanism to retrieve a specific cookie’s value directly. This requires parsing through the string to locate the desired cookie value. To do that, you need to edit the functions.php file as shown earlier and create a function that uses the document.cookie property. The syntax for that is shown below:

function getCookie(cookieName) {
    let name = cookieName + “=”;
    let decodedCookie = decodeURIComponent(document.cookie);
    let ca = decodedCookie.split(‘;’);
    for(let i = 0; i < ca.length; i++) {
        let c = ca[i];
        while (c.charAt(0) == ‘ ‘) {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return “”;
}

Using this function, you can retrieve the value of a specific cookie easily. For example, to get the value of a cookie named user_theme, you can use:

let userTheme = getCookie(“user_theme”);

This will store the value of user_theme in the userTheme variable, if the cookie exists. If not, it will return an empty string. Save and re-upload the file to your site and you are done.

How to Delete cookies in WordPress

Deleting cookies in WordPress is a crucial task, especially when managing user sessions or after a user logs out. Similar to setting and getting cookies, deleting them is handled within the functions.php file of your theme.

To delete a cookie in PHP, you can use the setcookie() function again, but with the expiration parameter set to a time in the past. This makes the cookie invalid, and the browser will automatically remove it.

Here are the steps to do that:

Step 1: Obtain your site’s FTP credentials (host IP address, username, password, and port number, if applicable) and use a client like Filezilla to access your site.

Step 2: Navigate to the directory of your site’s current theme. Usually it is in the location: /public_html/wp-content/themes/theme_name. Create a child theme out of it for safety and update reasons. Locate the functions.php file for the child theme, right-click on it, and click on View/Edit. This opens the file in your preferred file editor application.

Step 3: At the end of the file, add the following code:

if(isset($_COOKIE[‘user_login’])) {
    unset($_COOKIE[‘user_login’]); 
    // Set the cookie expiration date to one hour ago
    setcookie(‘user_login’, ”, time() – 3600, ‘/’); 
}

This code checks if the user_login cookie is set. If it is, it unsets it from the $_COOKIE array and then calls setcookie() with an expiration date of one hour ago, effectively removing it from the browser.

Step 4: Save the file and close the file editor window. This brings up a pop-up that asks whether you wish to upload the edited file to the server. Click on Yes and you are done. You can now return to your site’s wp-admin dashboard and apply the child theme to delete your cookie/s.

Note: Much like creating and getting a cookie, you can delete one using JavaScript as well. To delete a WordPress cookie, you can set the cookie’s expiration date to a past date in a similar way to PHP. Since JavaScript does not have a direct method to delete cookies, this approach tells the browser to expire the cookie immediately.

To do that, simply edit the functions.php file as shown above and create a simple function to use the document.cookie property. Here is the syntax to do that:

function deleteCookie(cookieName) {
    document.cookie = cookieName + ‘=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/’;
}

Using this function, you can delete a cookie by simply passing its name:

deleteCookie(“user_theme”);

This will remove the user_theme cookie by setting its expiration date to a time far in the past, causing the browser to discard it. Save and re-upload the file to your site and you are done.

How to Secure WordPress cookies

Securing WordPress cookies is essential to protect your website and your users from serious security threats like cookie stealing attacks. While a robust firewall like MalCare’s Atomic Security is the best defense against such attacks, here are some other strategies you can implement to enhance cookie security.

Set a short expiry date

Regardless of how a cookie is created—using PHP or JavaScript—setting a short expiry date is a key security measure. This is particularly important for cookies that store critical or sensitive information like user details. A shorter lifespan ensures that even if the cookie data is somehow intercepted or accessed maliciously, it will be valid for a limited time only.

Example in PHP:

setcookie(“user_session”, “session_data”, time() + (3600), “/”); // Expires in 1 hour

Example in JavaScript:

document.cookie = “user_session=session_data; max-age=3600; path=/”; // Expires in 1 hour

Set the secure flag (PHP-only)

This method applies exclusively to cookies created with PHP. When you set the secure flag, you ensure that the cookie is sent only over secure HTTPS connections. This precaution prevents cookies from being transmitted over unsecured HTTP connections, thus reducing the risk of man-in-the-middle attacks.

Example:

setcookie(“secure_user_session”, “secure_data”, time() + (3600), “/”, “”, true);

In this example, setting the sixth parameter (true) activates the secure flag, binding the cookie to HTTPS connections only.

Set the httponly flag (PHP-only)

Much like the secure flag, the httponly flag applies to cookies managed with PHP. Setting this flag ensures that the cookie is accessible only over HTTP(S) connections, making it inaccessible to client-side scripts like JavaScript. This limitation is particularly effective in mitigating the risk of cross-site scripting (XSS) attacks, as it prevents malicious scripts from accessing the cookie data.

Example:

setcookie(“http_only_user_session”, “http_only_data”, time() + (3600), “/”, “”, false, true);

By setting the last parameter (true) in the setcookie() function, the httponly flag is activated, enhancing the cookie’s resistance to XSS attacks.

Understanding third-party cookies

When browsing WordPress sites, you may also encounter another type of cookie, other than the ones mentioned above. These are called third-party cookies. While first-party cookies are set by the site you’re visiting, aiding in functionalities like keeping you logged in, third-party cookies come from other sources and not the site you’re directly interacting with. They are often used for advertising, analytics, and social media integration.

Imagine visiting a WordPress blog about travel. This blog might use first-party cookies to remember your language preferences or login status. However, if the blog displays ads from an advertising network or incorporates social media sharing buttons, these external services set their own cookies on your device. These are third-party cookies. They are mainly used for cross-site tracking, retargeting, and ad-serving.

Let’s say you visit several sites about outdoor sports, and these sites use the same advertising network. This network places a third-party cookie on your browser to track your interests. Later, you might notice ads for camping gear on different websites you visit. That’s third-party cookies at work, allowing advertisers to show you relevant ads by tracking your online behavior across multiple sites.

Here are some examples of how third-party cookies are used on WordPress sites:

Google Analytics: A widely used tool among WordPress site owners. When integrated into a site, it uses third-party cookies to collect data on site visitors’ behavior. This helps site owners understand visitor interactions and improve the user experience.

Social media plugins: If your WordPress site includes social sharing buttons (like “Share on Facebook” or “Tweet”), these features use third-party cookies. They enable these platforms to track users across websites for personalizing and measuring their ads.

Ad networks: WordPress sites using advertising networks (like Google AdSense) to monetize their content will have these networks set third-party cookies on visitors’ browsers. This is for tracking the effectiveness of ads across different sites and targeting ads based on user behavior.

It’s worth noting that the use of third-party cookies is undergoing changes due to increasing privacy concerns and regulatory actions (e.g., GDPR in Europe, CCPA in California, etc.). Browsers like Safari and Firefox have already started blocking third-party cookies by default, and Google Chrome plans to phase them out.

Cookies and consent

In today’s digital landscape, the storage of information using cookies isn’t just a matter of functionality—it’s a significant ethical and legal concern. At the heart of this issue is user consent. Ideally, users should have the autonomy to choose if and what kind of information can be captured and stored through cookies on their devices. This is crucial not only from a privacy perspective but also for fostering trust between website owners and users.

Ethical considerations and GDPR

The introduction of the General Data Protection Regulation (GDPR) in the European Union has placed these ethical considerations into a legal framework. GDPR mandates that users must provide informed consent before their data can be collected. This means website visitors must be made aware of the cookies a site intends to set, what information these cookies will track, and for what purpose.

For website owners and administrators, this translates into an obligation to seek and obtain user consent before any cookies are set on the user’s device, especially if these cookies are used to collect personal data. It’s important to note that consent must be explicit and informed, which leads to the necessity of implementing a clear and user-friendly consent mechanism.

Implementing consent mechanisms

How do you comply with these requirements in practice? Fortunately, WordPress site owners have a variety of tools at their disposal to simplify this process. Plugins play a significant role here, with options such as CookieYes, Cookie Notice & Compliance for GDPR/CCPA, and others designed specifically to manage cookie consent in line with legal requirements.

These plugins typically work by presenting users with a consent banner or pop-up when they first visit a site. This banner informs users about the use of cookies and requests their permission to proceed. Users then have the opportunity to accept all cookies, reject non-essential cookies, or customize their preferences regarding different categories of cookies. Not only does this approach align with legal obligations under laws like GDPR, but it also empowers users, giving them control over their data and enhancing their trust in the website.

Final thoughts

When it comes to using cookies on a WordPress site, it’s all about balance. Cookies help make websites more user-friendly. They remember user details so they don’t have to fill them in every time. But they also raise questions about privacy and safety. Website owners have to be careful about this. They need to tell users about the cookies and protect their data from any risks. Making sure everyone knows what’s happening with their info is key to keeping their trust.

Keeping your website safe and respecting users’ privacy is really important. Handling cookies correctly is a big part of this. You need to make sure that when you use cookies, you do it safely and let your visitors know why. Doing this helps keep your site safe and builds trust with your users. A trustworthy website is good for everyone.

FAQs

What are WordPress cookies?

WordPress cookies are small files that a WordPress site sends to a user’s browser, which the browser then stores on the user’s device. These cookies are used by WordPress to manage user sessions, store user preferences, and perform other tasks that enhance the user experience or enable site functionality.

Can I set a cookie using JavaScript in WordPress?

Yes, you can set a cookie using JavaScript in WordPress. However, JavaScript does not have an in-built function to set cookies. Hence, you will need to define a JavaScript function that sets the cookie by specifying its name, value, and expiration date, and then call that function at the appropriate time in your site’s logic.

What are site cookies used for?

Site cookies are used for a variety of purposes, each aimed at enhancing the user experience, enabling website functionalities, and collecting data for site improvement and marketing strategies. Some of their main uses are user authentication, user preference management, tracking and analytics, advertising, etc.

Why are they called cookies?

The term “cookies” in the context of web technology is believed to be derived from “magic cookies.” This term was originally used in the programming world to describe a piece of data a program receives and sends back unchanged, a common method for managing sessions and transactions in distributed computing systems. The concept of a magic cookie predates the web and was used in several forms of computing environments.

Where can I find more information about handling cookies in WordPress?

The official WordPress Codex and developer documentation are great sources of information for handling cookies. Additionally, resources like the GDPR and privacy law websites can provide legal insights regarding cookies and user consent.

The post How to set, get, and delete cookies in WordPress appeared first on MalCare.

Posted in

About Us

I believe that everyone should have a mechanic that they can trust and after spending several years helping out various customers for large companies I've seen my fair share of issues.

Honesty, Integrity, and Compassion are what we share with everyone that we work with. Stop scouring the internet for help and see how we can help you today.

Our Services

Website Migrations

Plugin & Theme Updates

IDX Broker Customizations

Facebook Chatbots

DNS & Email Integrations