How to Set, Get and Delete Cookies in WordPress

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.

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!

More from this author

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:

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.

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.

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 );
exit;

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!

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.

Free Guide:

7 Habits of Successful CTOs

"What makes a great CTO?" Engineering skills? Business savvy? An innate tendency to channel a mythical creature (ahem, unicorn)? All of the above? Discover the top traits of the most successful CTOs in this free guide.