Do you want to learn how to use cookies on your WordPress site? Cookies are a useful tool to store temporary information in user’s browser and then use this information to enhance user experience through personalization and behavioral targeting. In this ultimate guide, we will show you how to set, get, and delete WordPress cookies like a pro.
Note: This is an advanced tutorial. It requires you to have proficient understanding of HTML, CSS, WordPress site, and PHP.
What Are Cookies?
Cookies are plain text files that are created and stored in users browser when they visit a website. Cookies are used to add different features on a website.
Following are some of the common usage of cookies on various websites.
- Store and manage user’s login information
- Store temporary session information during a users visit
- Ecommerce stores use cookies to remember cart items during a user’s visit
- Track user activity on a site to offer personalized user experience
- and more
As you can see, cookies are highly useful tool for website owners, but they can also be a bit invasive. Recent trends in email marketing, growth hacking, and online marketing as a whole allow websites to set cookies that act as a beacon and can be used to store and even share user activity across websites.
This is why European Union enacted the EU Cookie Law, which requires website owners to declare that they use cookies to store information.
How Cookies are Used in a Typical WordPress Website
By default, WordPress uses cookies to manage logged-in user sessions and authentication. It also uses cookies to remember a user’s name and email address if they fill out a comment form.
However, many WordPress plugins on your website may also set their own cookies. For example, OptinMonster allows you to show different email optin forms to new vs returning visitors, and it does that by using cookies.
If you are using third party services on your website like Google Analytics or Google AdSense, then they may also set cookies on your website.
You can view all website cookies in your browser’s settings. For example, in Google Chrome you need to go to settings and search for ‘content settings’.
Under content settings, you will need to click on ‘Cookies’ to open the cookies settings page.
Next, you need to click on the ‘All cookies and site data’ option.
On the next page, you will see a list of all cookies and site data stored on your browser by all websites you visited.
You can type a website address in the search box, and it will show you the data stored by that website.
Clicking on a single item will show you more details about individual cookies and their contents.
How to Set a Cookie in WordPress
To follow this tutorial, you will need to add code to your theme’s functions.php file or a site-specific plugin. If you haven’t done this before, then please take a look at our guide on how to copy and paste code snippets in WordPress.
First we will use the setcookie()
function in PHP. This function accepts the following parameters.
- Cookie name
- Cookie value
- Expire (Optional: sets a time period after which cookie expires)
- Path (Optional, by default it will use the site’s root)
- Domain (Optional, by default uses your website’s domain)
- Secure (Optional, If true then only transfers cookie data via HTTPS)
- httponly (Optional, when set true the cookie is only accessible via HTTP and cannot be used by scripts)
Now let’s add a code snippet to your WordPress site. This code stores the exact timestamp when a user visited your website in a cookie.
function wpb_cookies_tutorial1() { $visit_time = date('F j, Y g:i a'); if(!isset($_COOKIE[wpb_visit_time])) { // set a cookie for 1 year setcookie('wpb_visit_time', $visit_time, time()+31556926); } }
You can now visit your website and then check your browser cookies. You will find a cookie with the name wpb_visit_time
.
How to Get a Cookie and Use it in WordPress
Now that we have created this cookie that’s stored in user’s browser for 1 year, let’s take a look at how can we use this information on our website.
If you know the name of a cookie, then you can easily call it anywhere in PHP using the $_COOKIE[] variable. Let’s add some code that not only sets the cookie but also uses it to do something on your website.
function wpb_cookies_tutorial2() { // Time of user's visit $visit_time = date('F j, Y g:i a'); // Check if cookie is already set if(isset($_COOKIE['wpb_visit_time'])) { // Do this if cookie is set function visitor_greeting() { // Use information stored in the cookie $lastvisit = $_COOKIE['wpb_visit_time']; $string .= 'You last visited our website '. $lastvisit .'. Check out whats new'; return $string; } } else { // Do this if the cookie doesn't exist function visitor_greeting() { $string .= 'New here? Check out these resources...' ; return $string; } // Set the cookie setcookie('wpb_visit_time', $visit_time, time()+31556926); } // Add a shortcode add_shortcode('greet_me', 'visitor_greeting'); } add_action('init', 'wpb_cookies_tutorial2');
We have commented the code to show you what each part does. This code uses the information stored in the cookie and outputs it using the shortcode. You can now add shortcode [greet_me] anywhere on your website, and it will show when a user last visited.
Feel free to modify the code to make it more useful for your website. For example, you can show recent posts to returning users and popular posts to new users.
Deleting a Cookie in WordPress
So far we have learned how to set a cookie and use it later in your website. Now let’s take a look at how to delete a cookie.
To delete a cookie, you need to add the following line to your code.
unset($_COOKIE['wpb_visit_time']);
Don’t forget to replace wpb_visit_time with the name of the cookie you are trying to delete.
Let’s put this code in some context using the same sample code we used above. This time we will delete a cookie and set it again with new information.
function wpb_cookies_tutorial2() { // Time of user's visit $visit_time = date('F j, Y g:i a'); // Check if cookie is already set if(isset($_COOKIE['wpb_visit_time'])) { // Do this if cookie is set function visitor_greeting() { // Use information stored in the cookie $lastvisit = $_COOKIE['wpb_visit_time']; $string .= 'You last visited our website '. $lastvisit .'. Check out whats new'; // Delete the old cookie so that we can set it again with updated time unset($_COOKIE['wpb_visit_time']); return $string; } } else { // Do this if the cookie doesn't exist function visitor_greeting() { $string .= 'New here? Check out these resources...' ; return $string; } } add_shortcode('greet_me', 'visitor_greeting'); // Set or Reset the cookie setcookie('wpb_visit_time', $visit_time, time()+31556926); } add_action('init', 'wpb_cookies_tutorial2');
As you can see, this code deletes the cookie once we have used the information stored inside. Later we set the cookie again with the updated time information.
We hope this article helped you learn how to easily set, get, and delete WordPress cookies. You may also want to see our list of other extremely useful tricks for the WordPress functions file.
If you liked this article, then please subscribe to our YouTube Channel for WordPress video tutorials. You can also find us on Twitter and Facebook.
Thanks for the awesome tutorial!
A small mistake: In the first code snippet $wpb_visit_time should be ‘wpb_visit_time’
Thanks for catching that, we’ll be sure to update the code
Hi there, you seem to have an error in your code for the first example:
function wpb_cookies_tutorial1() {
$visit_time = date(‘F j, Y g:i a’);
if(!isset($_COOKIE[$wpb_visit_time])) {
// set a cookie for 1 year
setcookie(‘wpb_visit_time’, $current_time, time()+31556926);
}
}
You specify the variable as $visit_time but in the setcookie function you call $current_time.
Thank for the guide(s) though they are super useful.
Thanks for pointing that out, we will be sure to update and fix that, glad our guides have been useful
Your articles are really helpful but I need to understand the codings very well so I want to know,
Do I have to copy and paste all the code displayed here?
Do I replace wbp_visit_time, wbp_cookies_tutorial with the name of my site?
For understanding how to add the code, you would want to take a look at our article below:
https://www.wpbeginner.com/beginners-guide/beginners-guide-to-pasting-snippets-from-the-web-into-wordpress/
You do not need to replace the names with the name of your site.
I don’t know why anytime I try to search my website using any search engines it writes website not trusted
What’s wrong? How can My website be trusted by all browsers and search engines?
You may want to ensure your site is using HTTPS and take a look at our guide below:
https://www.wpbeginner.com/wp-tutorials/how-to-add-ssl-and-https-in-wordpress/
Apologies for resurrecting this thread but i need some help.
The first page of my site asks customers to select their region. The products available will differ depending on where they choose.
I don’t want them to have to re-select this location every time they go to the homepage.
Any advice?
You would want to check with the support for your eCommerce plugin for if they have a method to set that for your users.
Great article. You said to put the code in the functions.php file. I am using WP Elementor, I only need the cookie values pulled up when a user goes to a certain page. Can this code be added on a specific page? I want to create the cookie with certain values that come from a form, the first time the user completes the form. After that, the next time they come back to this page, the form should auto populate from the cookie data., this reduces the fields they need to complete on a return visit.
For that, you would want to reach out to the form plugin you are using for if they have a system for that already set up.
You can add the code to functions.php and use the WordPress function “is_page()” to add conditional logic to your cookie code snippet.
The is_page() function accepts either page ID, slug or name/title. It’s pretty easy to use, you can read more about the is_page() function online in the WordPress codex.