Close

WordPress Cookies

Cookies and WordPress: How to Set, Get and Delete

Everyone loves an occasional cookie (or two) offline but their virtual use in sites worldwide is often a topic of confusion.

Cookies offer a simple and elegant solution to do things like maintain sessions for your visitors as they browse, store user preferences and gather data for your site.

In this article, we’ll cover everything you need to know about cookies: what they are, where they’re used, and why we use them (and not eat them).

I’ll also explain why we need to be able to use cookies with WordPress and we’ll finish up with how to manually set, get and delete cookies from your WordPress site.

Let’s get snacking cracking!

Cookies Explained

Though their use is pretty much omnipresent across the web, the average user tends to know little about what cookies are and how they’re used. Let’s walk through some basics to get up to speed.

What Are Cookies?

A cookie is a small file browsers use to store information about a user’s interaction with a site. They’ll typically be used to persistently store various types of session data. The Guardian has a great no-nonsense overview of cookies which you can enjoy below.

What Are Sessions?

A session is kind of like a digital ID card; each time when you visit a website you’ll be assigned one for the duration of your visit and it will be used to identify you during your time on the site. Sessions are unique to users.

Why Use Cookies and Maintain Sessions?

There are many valid reasons for using a combination of sessions and cookies to track user behavior and store info. Here are some common scenarios:

  • When you add items to your shopping cart on an e-commerce site, the website stores that information so that your cart is updated as you keep shopping and move from page to page.
  • If you like to read news online, the site can store your IP information and show you stories based on your geographical location.
  • Cookies also store information used to authenticate a user on a particular website. A user’s login information is saved and reloaded when the user returns to the site. This way you no longer have to remember your usernames and passwords for every site you sign up on. Hallelujah!

Types of Cookies

Like their real-world counterparts, cookies come in different flavors:

  • Session Cookies: These cookies store information about the activities users perform during a single session. They are used to persist data about your activities as you browse through a site but are erased at the end of your session.
  • Persistent Cookies: You’ll also hear these referred to as tracking cookies. Persistent cookies remain on your hard drive until they expire or are erased. These are often used to manage user preferences over longer periods of time.

Laws Governing the Use of Cookies

Those of you who don’t like the concept of a website storing personal information about you might be wondering whether any of this is even legal?

The European Union has taken a stand on the issue in the form of EU Directive 2009/136/EC – you’ll usually hear the relevant details referred to as the EU Cookie Law. To cut a long story short, the legislation says that sites in Europe must ask visitors for their consent before installing certain types of cookies.

Outside of Europe, the question of exactly how you can use cookies as a site owner is largely at your own discretion but the recent kerfuffle over increasingly aggressive user monitoring by advertisers shows that users are increasingly wary about how they’re tracked.

Is My Site Using Cookies?

If you’d like to see if your site or another is saving cookies in your browser, follow this simple procedure (for Chrome):

Go to your browser's settings to control cookies.
Go to your browser’s settings to control cookies.

Go to Settings and then click Show advanced settings… In the “Privacy” section click on Content Settings. A modal will display giving you options for how you want to store cookies on your site. Leave as is and go to All cookies and site data.

The next window will display the cookies that your browser has currently saved.

Let’s take a closer look at the information saved in the popup_signup_completely variable for the premium.wpmudev.org cookie:

Among the list of cookies my browser has saved are cookies for WPMU DEV.
Among the list of cookies my browser has saved are cookies for WPMU DEV.

In this case, it’s a simple record of whether a popup window has already been shown to a user so they don’t need to be continually bothered by it.

Let’s turn our attention now to cookies in a WordPress context.

Why Do We Need Cookies in WordPress?

WordPress does not use sessions by default. It displays the same behavior regardless of the user navigating the site. It stores a cookie for user authentication when you (or your staff) login to the site’s backend but that’s just about it.

Being pretty much stateless, WordPress itself will not give you the functionality to create shopping carts using cookies or retrieve visitors’ personal data via cookie to improve user experience – it’s got a lot of things going for it out of the box, but cookies just aren’t one of them.

It’s important to note here that WordPress itself does not maintain sessions but many plugins or themes you may have activated almost certainly do. So, if you found some of your WordPress site’s cookies saved in your browser, chances are it was implemented by one of these.

Let’s move on to manually creating, retrieving and deleting cookies.

Cookie Manipulation in WordPress

Before we jump into the code, there are a few things you should know first:

  • We’ll send cookies in HTTP headers
  • The code will be in PHP and is to be added to functions.php in the active theme’s directory

We’re doing it this way to keep things simple and for explanatory purposes. In a production environment, there are several excellent reasons for not using functions.php to do this sort of thing.

How to Set Cookies

To set cookies in WordPress, you have to pass in the values that you want to store. For instance, if you’d like to store your visitor’s username, you might add this code snippet to the functions.php file:

view raw cookie-setting hosted with ❤ by GitHub

The DAYS_IN_SECONDS variable holds a constant value provided by WordPress which equals the number of seconds in a day. Notice that the time value is set for 30 * DAYS_IN_SECONDS which means that the cookie will expire 30 days after creation. COOKIEPATH defines the path to your site and COOKIE_DOMAIN is the site’s domain – both these variables are set by your site.

When we run the function we can see that the cookie has been added to the browser by following the steps we looked at for viewing browser cookies earlier in the article.

How to Get Cookies

In order to retrieve the cookie we created in the code above, we will utilize the $_COOKIE variable. This variable is an associative array that we will use to reference the cookie we created.

The $_COOKIE variable contains information about all of the cookies that are manually added to your browser and to get the one we’re looking for we’ll have to pass in an identifier. The identifier we will use in this case will be the name we gave the cookie when we were setting it. Let’s take a look at the code.

view raw cookie-get hosted with ❤ by GitHub

Before we pass the cookie’s identifier (in this case, its name) into the $_COOKIE variable, we must make sure that the cookie exists. We accomplish this via the isset() function which 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. You do not have to put in extra steps to encrypt your visitor’s information.

How to Delete Cookies

There’ll be times where you want to delete cookies from your site, typically when you no longer want a particular bit of information. Let’s look at the code first and then move on to the explanation.

view raw delete-cookie hosted with ❤ by GitHub

First of all, we use the unset() function to remove the value the cookie holds from the associative array. Once that’s done, we will force the cookie to expire by setting its value variable to a null value (“”) and passing in a timestamp that’s in the past (time() - ( 15 * 60 )).

Congratulations, your cookie is now deleted. What do you do now? Once the cookie has been removed, you might want to redirect your visitors to your homepage. To do this, add the following two lines of code to the functions.php file:

wp_redirect( home_url(), 302 );
exit;

This code snippet will redirect your site’s visitors to the homepage but you can redirect them anywhere you’d like on your site simply by changing the first argument.

Final Thoughts

Cookies are a big part of what makes the web keep ticking along and, even if you never have to get your hands dirty with actually coding them, it’s useful to have an idea of roughly how they work.

We’ve covered the basics of what cookies are and how you can go about checking which ones are stored on your machine. We’ve also stepped through some simple ways of setting, getting and deleting cookies in the context of WordPress using PHP.

Hopefully, this tutorial will help start you down the road of exploring cookies and session management in more depth in the future.

Do you currently use cookies to enhance user experience? Or do you have other techniques to recommend for setting, getting and deleting cookies in WordPress? Let us know in the comments below.