How to Set, Get and Delete Cookies in WordPress

Share this article

Unlike most modern web applications, WordPress is stateless. If you’re going to build a web application on top of WordPress, you’re going to need some sort of a system to maintain sessions.

How to Set, Get and Delete Cookies in WordPress

Cookies provide a simple, conventional mechanism to manage certain settings for users who have signed in on the front-end.

In this article, we’ll briefly discuss cookies, why they’re needed in WordPress and how webmasters can benefit from them. We’ll also walk you through the process of setting, getting and deleting cookies.

Let’s get started!

An Overview of Cookies

A cookie is a small piece of data that is sent by a website to a user’s web browser. The cookie contains information about the user, such as their username/password, items they may have added to their cart on e-commerce sites, etc. When the user visits the site again, the cookie is sent back by the browser and it lets the site know of the user’s previous activity.

Often times, cookies are encrypted files. The purpose of cookies is to assist users. When a site you frequently visit remembers your username and password you don’t have to re-authenticate yourself every single time. When you’re shopping online, cookies will help the site show you items that you’re more likely to buy.

As you can see, cookies are important to a site. We’ll show you how you can add cookie functionality to your WordPress site.

Before we get into the code let’s discuss some preliminaries:

  • We will be using PHP code in this tutorial.
  • We will be sending the cookie in the HTTP headers.
  • We will run all functions at init action.
  • The code is to be added to the function.php file in the active theme directory.

Setting Cookies in WordPress

Why Do We Need to Set Cookies?
When users visit your web application, they’ll enter their information (usernames, passwords, personal details etc) in a form on the front-end. Your site should somehow notify them that their information will be saved in a cookie. For example, some sites let the user opt-in for the “Remember me” option.

We’ll set cookies in WordPress using the setcookie() function so that we can retrieve its value later on and modify it, if needed. A high level view of the process suggests that we’ll be sending the cookie along with the other HTTP headers.

How to Set Cookies
The setcookie() function is pretty straightforward. The syntax is as follows:

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

All you have to do is pass in the values that you want to store. If you want to store your visitor’s username, the code should look something like this:

    add_action( 'init', 'my_setcookie_example' );
    function my_setcookie_example() {
   setcookie( $visitor_username, $username_value, 3 * DAYS_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN );

Notice that the time value is set for three days which means that the cookie will expire three days after creation. The DAYS_IN_SECONDS value is a constant provided by WordPress. You don’t have to worry about the last two parameters – WordPress defines them on its own. COOKIEPATH defines the path to your site whereas COOKIE_DOMAIN is the site’s domain.

If you’re more proficient with PHP coding you can set the expiration time based on user input. Have you ever come across a site that asked “Remember me for X days”? They follow the same principle of setting cookie expiration based on the value X the user enters/selects.

When we run the function we can see that the cookies have been added to the browser. In order to modify a cookie, all you have to do is set the cookie again using the setcookie() function.

Getting Cookies in WordPress

Why Do We Need to Get Cookies In WordPress?
Once you’ve created cookies, you’ll need to retrieve data from them when your visitors returns to your site. To prevent any unnecessary errors, we’ll first use the isset() function to determine if the cookie has some value in it i.e. if it was set or not.

If the cookie was set, we’ll echo the value to be retrieved in order to display it.

How to Get Cookies in WordPress
To retrieve the cookie we created in the example above, we’ll use the $_COOKIE variable which is essentially an associative array. To get the value of the cookie we created, we’ll need to locate it by name in the array.

    if(!isset($_COOKIE[$visitor_username])) {
    echo "The cookie: '" . $visitor_username . "' is not set.";
    } else {
    echo "The cookie '" . $visitor_username . "' is set.";
    echo "Value of cookie: " . $_COOKIE[$visitor_username];

Notice that before we actually pass the cookie’s name into the $_COOKIE variable, we must make sure that the cookie was set. In the example above, we did this by using the isset() function. The isset() function returns TRUE if the cookie has been set and FALSE otherwise.

A key point to note here is that when we set a cookie and send it in the HTTP header, its value is URL encoded automatically. Similarly, when we retrieve the cookie the value is decoded by default. If, for some reason, you’d like to avoid URL encoding the cookie when it’s sent you can use the setrawcookie() function instead.

Deleting Cookies in WordPress

Why Do We Need to Delete Cookies in WordPress?
Now that you’ve successfully set and retrieved cookies you’re probably wondering how we’ll delete them. Do we need a new function? The answer is no.

As I mentioned before, cookie manipulation in WordPress is simple. To delete (or unset) a cookie we’ll unset the cookie and then use the same function we used to set it in order to delete it. Is that a little confusing? Don’t worry, just hang in there. The only thing different will be the expiration date.

    unset( $_COOKIE[$visitor_username] );
    setcookie( $visitor_username, '', time() - ( 15 * 60 ) );

In the first line of the code, we’re using the unset() function to remove the value of the cookie from the $_COOKIE associative array. In the second line, we force the cookie to expire by setting its value to an empty value and passing in a timestamp that’s in the past.

The first parameter is the name of the cookie variable, the second parameter is a null value and the third parameter denotes 15 minutes (15 * 60) in the past.

When you’ve deleted the cookie, you’ll want to redirect your visitors to the WordPress home page. To do this, add the following code to the file:

wp_redirect( home_url(), 302 );

You do not necessarily have to redirect the user to the WordPress home page immediately. You can follow cookie deletion with other housekeeping tasks. But sooner or later you will have to redirect the user to another page and, conventionally speaking, it should be the home page.

Wrapping It Up

In this article, we walked through a simple tutorial to set, get and delete cookies in WordPress using PHP. We also covered some of the variables you’ll encounter during the procedure and what they actually do.

Cookie manipulation in WordPress is easy for anyone who understands the basics of PHP – and for those who do not, now they know!

You can also check out the official documentation on WordPress and cookies here.

Have you encountered any issues with cookie manipulation? Is there another method you follow to set, get or delete cookies? We’d love to hear from you in the comments section below.

Frequently Asked Questions (FAQs) about Setting, Getting, and Deleting Cookies in WordPress

What are the benefits of using cookies in WordPress?

Cookies play a crucial role in enhancing user experience on a WordPress site. They store small amounts of data on the user’s device, which can be used to remember user preferences, login details, and shopping cart contents. This makes the browsing experience more personalized and convenient. Cookies can also be used for tracking user behavior on the site, which can provide valuable insights for improving the site’s content and layout.

How can I set a cookie in WordPress?

Setting a cookie in WordPress is quite straightforward. You can use the setcookie() function provided by PHP. This function takes several parameters including the name of the cookie, its value, expiration time, path, domain, and security settings. Remember to set the cookie before sending any output to the browser, as cookies are part of the HTTP header.

How can I retrieve a cookie’s value in WordPress?

To retrieve the value of a cookie in WordPress, you can use the $_COOKIE superglobal array in PHP. This array contains all the cookies that are currently accessible by the script. You can access a specific cookie’s value by its name, like this: $_COOKIE[‘cookie_name’].

How can I delete a cookie in WordPress?

To delete a cookie in WordPress, you can use the setcookie() function again, but this time set the expiration time to a past date. This will cause the browser to immediately discard the cookie.

Are there any security concerns with using cookies in WordPress?

While cookies are generally safe, they can pose some security risks if not handled properly. For example, if sensitive information is stored in cookies without proper encryption, it can be intercepted and exploited by malicious parties. Therefore, it’s important to always use secure, encrypted connections when dealing with cookies, and to never store sensitive information in cookies.

Can I control which cookies are set by my WordPress site?

Yes, as a site administrator, you have full control over which cookies are set by your WordPress site. You can choose to set cookies for various purposes such as user authentication, session tracking, and user preference storage.

How can I ensure that my use of cookies complies with privacy laws?

To ensure compliance with privacy laws, you should always inform your users about your use of cookies and obtain their consent before setting any non-essential cookies. You should also provide a clear and accessible privacy policy that explains how you use cookies and how users can manage their cookie preferences.

Can users disable cookies on my WordPress site?

Yes, users have the ability to disable cookies in their browser settings. However, this may affect the functionality and user experience of your site. It’s important to make users aware of this in your site’s cookie policy.

How can I test if a cookie is working correctly on my WordPress site?

You can test if a cookie is working correctly by setting the cookie and then trying to retrieve its value. If you can successfully retrieve the correct value, then the cookie is working as expected.

Can I use cookies to track user behavior on my WordPress site?

Yes, cookies are commonly used for tracking user behavior on websites. By setting a unique identifier in a cookie, you can track a user’s actions and preferences across multiple sessions and visits. This can provide valuable insights for improving your site’s content and user experience.

Rafay Saeed AnsariRafay Saeed Ansari
View Author

Rafay is an entrepreneur, computer scientist, and professional ghost-writer for several high-traffic websites. He provides byline and ghost-writing services for digital and brick-and-mortar businesses with a focus on web development, WordPress, and entrepreneurship.

Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week
Loading form