{"id":146618,"date":"2015-09-30T11:00:53","date_gmt":"2015-09-30T15:00:53","guid":{"rendered":"http:\/\/premium.wpmudev.org\/blog\/?p=146618"},"modified":"2022-03-08T04:45:36","modified_gmt":"2022-03-08T04:45:36","slug":"set-get-delete-cookies","status":"publish","type":"post","link":"https:\/\/wpmudev.com\/blog\/set-get-delete-cookies\/","title":{"rendered":"Cookies and WordPress: How to Set, Get and Delete"},"content":{"rendered":"<p style=\"text-align: left;\">Everyone loves an occasional cookie (or two) offline but their virtual use in sites worldwide is often a topic of confusion.<\/p>\n<p><a href=\"https:\/\/en.wikipedia.org\/wiki\/HTTP_cookie\" rel=\"noopener\" target=\"_blank\">Cookies<\/a> 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.<\/p>\n<p>In this article, we&#8217;ll cover everything you need to know about cookies: what they are, where they\u2019re used, and why we use them (and not eat them).<\/p>\n<p>I\u2019ll also explain why we need to be able to use cookies with\u00a0WordPress and we&#8217;ll finish up with how to manually set, get and delete cookies from your WordPress site.<\/p>\n<p>Let\u2019s get <span style=\"text-decoration: line-through;\">snacking<\/span> cracking!<\/p>\n<p>Here\u2019s what we\u2019re going to cover today:<\/p>\n<ul>\n<li><a href=\"#cookies-explained\">Cookies Explained<\/a>\n<ul>\n<li><a href=\"#what-are-cookies\">What Are Cookies?<\/a><\/li>\n<li><a href=\"#what-are-sessions\">What Are Sessions?<\/a><\/li>\n<li><a href=\"#why-use-cookies-and-maintain-sessions\">Why Use Cookies and Maintain Sessions?<\/a><\/li>\n<li><a href=\"#types-of-cookies\">Types of Cookies<\/a><\/li>\n<li><a href=\"#laws-governing-the-use-of-cookies\">Laws Governing the Use of Cookies<\/a><\/li>\n<li><a href=\"# is-my-site-using-cookies\">Is My Site Using Cookies?<\/a><\/li>\n<\/ul>\n<\/li>\n<li><a href=\"#why-need-cookies-in-wordpress\">Why Do We Need Cookies in WordPress?<\/a><\/li>\n<li><a href=\"#cookie-manipulation-in-wordpress\">Cookie Manipulation in WordPress<\/a>\n<ul>\n<li><a href=\"#set-cookies\">How to Set Cookies<\/a><\/li>\n<li><a href=\"#get-cookies\">How to Get Cookies<\/a><\/li>\n<li><a href=\"#delete-cookies\">How to Delete Cookies<\/a><\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<h2 id=\"cookies-explained\">Cookies Explained<\/h2>\n<p>Though their use is pretty much omnipresent across the web, the average user tends to know little about what cookies are and how they&#8217;re used. Let&#8217;s walk through some basics to get up to speed.<\/p>\n<h3 id=\"what-are-cookies\">What Are Cookies?<\/h3>\n<p>A cookie is a small file browsers use\u00a0to store information about a user&#8217;s interaction with a site. They&#8217;ll typically be used to persistently store various types of session data. <a href=\"http:\/\/www.theguardian.com\/us\/technology\" rel=\"noopener\" target=\"_blank\">The Guardian<\/a> has a great no-nonsense overview of cookies which you can enjoy below.<\/p>\n<p><span class=\"embed-youtube\" style=\"text-align:center; display: block;\"><span class=\"embed-youtube-lazy-id dev-hidden\">IPQhME1UYQU<\/span><\/span><\/p>\n<h3 id=\"what-are-sessions\">What Are Sessions?<\/h3>\n<p>A session is kind of like a digital ID card; each time when you visit a website you&#8217;ll be assigned one for the duration of your visit and it\u00a0will be used to identify you during your time on the site.\u00a0Sessions are unique to users.<\/p>\n<h3 id=\"why-use-cookies-and-maintain-sessions\">Why Use Cookies and Maintain Sessions?<\/h3>\n<p>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:<\/p>\n<ul>\n<li>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.<\/li>\n<li>If you like to read news online, the site can store your IP information and show you stories based on your geographical location.<\/li>\n<li>Cookies also store information used to authenticate a user on a particular website. A user\u2019s 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!<\/li>\n<\/ul>\n<h3 id=\"types-of-cookies\">Types of Cookies<\/h3>\n<p>Like their real-world counterparts, cookies come in different flavors:<\/p>\n<ul>\n<li><strong>Session Cookies: <\/strong>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.<\/li>\n<li><strong>Persistent Cookies: <\/strong>You&#8217;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.<\/li>\n<\/ul>\n<h3 id=\"laws-governing-the-use-of-cookies\">Laws Governing the Use of Cookies<\/h3>\n<p>Those of you who don\u2019t like the concept of a website storing personal information about you might be wondering whether any of this is even legal?<\/p>\n<p>The European Union has taken a stand on the issue in the form of <a href=\"http:\/\/eur-lex.europa.eu\/LexUriServ\/LexUriServ.do?uri=OJ:L:2009:337:0011:0036:En:PDF\" rel=\"noopener\" target=\"_blank\">EU Directive 2009\/136\/EC<\/a>\u00a0\u2013\u00a0you&#8217;ll usually hear the relevant details referred to as the <a href=\"https:\/\/gigaom.com\/2012\/05\/25\/cookie-law-explainer\/\" rel=\"noopener\" target=\"_blank\">EU Cookie Law<\/a>. 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.<\/p>\n<p>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 <a href=\"http:\/\/www.forbes.com\/sites\/valleyvoices\/2015\/09\/23\/ad-blocking-a-primer\/\" rel=\"noopener\" target=\"_blank\">increasingly aggressive user monitoring by advertisers<\/a> shows that users are increasingly wary about how they&#8217;re tracked.<\/p>\n<h3 id=\"is-my-site-using-cookies\">Is My Site Using Cookies?<\/h3>\n<p>If you\u2019d like to see if your site or another is saving cookies in your browser, follow this simple procedure (for Chrome):<\/p>\n<p>Go to <strong>Settings<\/strong> and then click <strong>Show advanced settings&#8230;<\/strong>\u00a0In the &#8220;Privacy&#8221; section click on <strong>Content Settings<\/strong>. A modal will display giving you options for how you want to store cookies on your site. Leave as is and go to\u00a0<strong>All cookies and site data<\/strong>.<\/p>\n<p>The next window will display the cookies that\u00a0your browser has currently saved.<\/p>\n<figure class=\"wp-caption aligncenter\" data-caption=\"true\"><img loading=\"lazy\" decoding=\"async\" class=\"attachment-490x490\" src=\"https:\/\/wpmudev.com\/blog\/wp-content\/uploads\/2015\/09\/content-settings3.png\" alt=\"Go to your browser's settings to control cookies.\" width=\"490\" height=\"312\" \/><figcaption class=\"wp-caption-text\">Go to your browser&#8217;s settings to control cookies.<\/figcaption><\/figure>\n<p>Let&#8217;s take a closer look at the information saved in the <code>popup_signup_completely<\/code>\u00a0variable for the wpmudev.com cookie:<\/p>\n<figure class=\"wp-caption aligncenter\" data-caption=\"true\"><img loading=\"lazy\" decoding=\"async\" class=\"attachment-735x735\" src=\"https:\/\/wpmudev.com\/blog\/wp-content\/uploads\/2015\/09\/cookies-and-site-data.png\" alt=\"Among the list of cookies my browser has saved are cookies for WPMU DEV.\" width=\"735\" height=\"655\" \/><figcaption class=\"wp-caption-text\">Among the list of cookies my browser has saved are cookies for WPMU DEV.<\/figcaption><\/figure>\n<p>In this case, it&#8217;s a simple record of whether a popup window has already been shown to a user so they don&#8217;t need to be continually bothered by it.<\/p>\n<p>Let&#8217;s turn our attention now to cookies in a WordPress context.<\/p>\n<h2 id=\"why-need-cookies-in-wordpress\">Why Do We Need Cookies in WordPress?<\/h2>\n<p>WordPress <a href=\"https:\/\/pantheon.io\/docs\/articles\/wordpress\/wordpress-and-php-sessions\/\" rel=\"noopener\" target=\"_blank\">does not use sessions by default<\/a>. 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\u2019s backend but that\u2019s just about it.<\/p>\n<p>Being pretty much stateless, WordPress itself will not give you the functionality to create shopping carts using cookies or retrieve visitors\u2019 personal data via cookie to improve user experience \u2013 it\u2019s got a lot of things going for it out of the box, but cookies just aren\u2019t one of them.<\/p>\n<p>It&#8217;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\u2019s cookies saved in your browser, chances are it was implemented by one of these.<\/p>\n<p>Let&#8217;s move on to manually creating, retrieving and deleting cookies.<\/p>\n<h2 id=\"cookie-manipulation-in-wordpress\">Cookie Manipulation in WordPress<\/h2>\n<p>Before we jump into the code, there are a few things you should know first:<\/p>\n<ul>\n<li>We\u2019ll send cookies in HTTP headers<\/li>\n<li>The code will be in PHP and is to be added to <em>functions.php<\/em> in the active theme\u2019s directory<\/li>\n<\/ul>\n<p>We&#8217;re doing it this way to keep things simple and for explanatory purposes. In a production environment, there are several excellent reasons for <a href=\"https:\/\/wpmudev.com\/blog\/why-you-shouldnt-use-functions-php\/\" target=\"_blank\" rel=\"noopener\">not using <em>functions.php<\/em><\/a> to do this sort of thing.<\/p>\n<h3 id=\"set-cookies\">How to Set Cookies<\/h3>\n<p>To set cookies in WordPress, you have to pass in the values that you want to store. For instance, if you\u2019d like to store your visitor\u2019s username, you might add this code snippet to the <em>functions.php<\/em> file:<\/p>\n<div class=\"gist\" data-gist=\"9eb6d4d9e33ee4a2c57bb67bea992468\" data-gist-file=\"new-cookie\"><a class=\"loading\" href=\"https:\/\/gist.github.com\/9eb6d4d9e33ee4a2c57bb67bea992468.js?file=new-cookie\">Loading gist 9eb6d4d9e33ee4a2c57bb67bea992468<\/a><div class=\"gist-consent-notice\" style=\"display:none\"><p>Please <a href=\"javascript:Cookiebot.renew()\">update your cookie preferences<\/a> to enable preference cookies to view this gist.<\/p><\/div><\/div>\n<p>The <code>DAY_IN_SECONDS<\/code> 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 <code>30 * DAY_IN_SECONDS<\/code> which means that the cookie will expire 30 days after creation. <code>COOKIEPATH<\/code> defines the path to your site and <code>COOKIE_DOMAIN<\/code> is the site\u2019s domain \u2013 both these variables are set by your site.<\/p>\n<p>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.<\/p>\n<h3 id=\"get-cookies\">How to Get Cookies<\/h3>\n<p>In order to retrieve the cookie we created in the code above, we will utilize the <code>$_COOKIE<\/code> variable. This variable is an associative array that we will use to reference the cookie we created.<\/p>\n<p>The <code>$_COOKIE<\/code> variable contains information about all of the cookies that are manually added to your browser and to get the one we\u2019re looking for we\u2019ll 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\u2019s take a look at the code.<\/p>\n<div class=\"gist\" data-gist=\"65fe7e1a742645b4e441cddc198010b3\" data-gist-file=\"cookie-get\"><a class=\"loading\" href=\"https:\/\/gist.github.com\/65fe7e1a742645b4e441cddc198010b3.js?file=cookie-get\">Loading gist 65fe7e1a742645b4e441cddc198010b3<\/a><div class=\"gist-consent-notice\" style=\"display:none\"><p>Please <a href=\"javascript:Cookiebot.renew()\">update your cookie preferences<\/a> to enable preference cookies to view this gist.<\/p><\/div><\/div>\n<p>Before we pass the cookie\u2019s identifier (in this case, its name) into the <code>$_COOKIE<\/code> variable, we must make sure that the cookie exists. We accomplish this via the <code>isset()<\/code> function which returns <code>TRUE<\/code> if the cookie has been set and <code>FALSE<\/code> otherwise.<\/p>\n<p>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\u2019s information.<\/p>\n<h3 id=\"delete-cookies\">How to Delete Cookies<\/h3>\n<p>There&#8217;ll be times where you want to delete cookies from your site, typically when you no longer want a particular bit of information. Let\u2019s look at the code first and then move on to the explanation.<\/p>\n<div class=\"gist\" data-gist=\"6b5dbad9be1e3012204b4200b915b49b\" data-gist-file=\"delete-cookie\"><a class=\"loading\" href=\"https:\/\/gist.github.com\/6b5dbad9be1e3012204b4200b915b49b.js?file=delete-cookie\">Loading gist 6b5dbad9be1e3012204b4200b915b49b<\/a><div class=\"gist-consent-notice\" style=\"display:none\"><p>Please <a href=\"javascript:Cookiebot.renew()\">update your cookie preferences<\/a> to enable preference cookies to view this gist.<\/p><\/div><\/div>\n<p>First of all, we use the <code>unset()<\/code> function to remove the value the cookie holds from the associative array. Once that\u2019s done, we will force the cookie to expire by setting its value variable to a null value (\u201c\u201d) and passing in a timestamp that\u2019s in the past (<code>time() - ( 15 * 60 )<\/code>).<\/p>\n<p>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 <em>functions.php<\/em> file:<\/p>\n<div class=\"gist\" data-gist=\"9ce62ede7ac343d171a14a4ff990e8fb\" data-gist-file=\"redirect-post-deletion\"><a class=\"loading\" href=\"https:\/\/gist.github.com\/9ce62ede7ac343d171a14a4ff990e8fb.js?file=redirect-post-deletion\">Loading gist 9ce62ede7ac343d171a14a4ff990e8fb<\/a><div class=\"gist-consent-notice\" style=\"display:none\"><p>Please <a href=\"javascript:Cookiebot.renew()\">update your cookie preferences<\/a> to enable preference cookies to view this gist.<\/p><\/div><\/div>\n<p>This code snippet will redirect your site\u2019s visitors to the homepage but you can redirect them anywhere you\u2019d like on your site simply by changing the first argument.<\/p>\n<h2>Final Thoughts<\/h2>\n<p>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&#8217;s useful to have an idea of roughly how they work.<\/p>\n<p>We\u2019ve covered the basics of what cookies are and how you can go about checking which ones are stored on your machine. We&#8217;ve also stepped through some simple ways of setting, getting and deleting cookies in the context of WordPress using PHP.<\/p>\n<p>Hopefully, this tutorial will help start you down the road of exploring cookies and session management in more depth in the future.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Cookies are the workhorse of much of the online world yet most people remain blissfully unaware of how and why they&#8217;re used. So we&#8217;re lifting the lid on the basics to show you how to create, retrieve and destroy your own cookies in the context of WordPress.<\/p>\n","protected":false},"author":37930,"featured_media":199236,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"blog_reading_time":"","wds_primary_category":0,"wds_primary_tutorials_categories":0,"footnotes":""},"categories":[235,263],"tags":[390,10248],"tutorials_categories":[],"class_list":["post-146618","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-misc","category-tutorials","tag-code","tag-cookies"],"_links":{"self":[{"href":"https:\/\/wpmudev.com\/blog\/wp-json\/wp\/v2\/posts\/146618","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/wpmudev.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/wpmudev.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/wpmudev.com\/blog\/wp-json\/wp\/v2\/users\/37930"}],"replies":[{"embeddable":true,"href":"https:\/\/wpmudev.com\/blog\/wp-json\/wp\/v2\/comments?post=146618"}],"version-history":[{"count":30,"href":"https:\/\/wpmudev.com\/blog\/wp-json\/wp\/v2\/posts\/146618\/revisions"}],"predecessor-version":[{"id":209587,"href":"https:\/\/wpmudev.com\/blog\/wp-json\/wp\/v2\/posts\/146618\/revisions\/209587"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/wpmudev.com\/blog\/wp-json\/wp\/v2\/media\/199236"}],"wp:attachment":[{"href":"https:\/\/wpmudev.com\/blog\/wp-json\/wp\/v2\/media?parent=146618"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/wpmudev.com\/blog\/wp-json\/wp\/v2\/categories?post=146618"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/wpmudev.com\/blog\/wp-json\/wp\/v2\/tags?post=146618"},{"taxonomy":"tutorials_categories","embeddable":true,"href":"https:\/\/wpmudev.com\/blog\/wp-json\/wp\/v2\/tutorials_categories?post=146618"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}