WPBeginner

Beginner's Guide for WordPress

  • Blog
    • Beginners Guide
    • News
    • Opinion
    • Showcase
    • Themes
    • Tutorials
    • WordPress Plugins
  • Start Here
    • How to Start a Blog
    • Create a Website
    • Start an Online Store
    • Best Website Builder
    • Email Marketing
    • WordPress Hosting
    • Business Name Ideas
  • Deals
    • Bluehost Coupon
    • SiteGround Coupon
    • WP Engine Coupon
    • HostGator Coupon
    • Domain.com Coupon
    • Constant Contact
    • View All Deals »
  • Glossary
  • Videos
  • Products
X
☰
Beginner's Guide for WordPress / Start your WordPress Blog in minutes
Choosing the Best
WordPress Hosting
How to Easily
Install WordPress
Recommended
WordPress Plugins
View all Guides

WPBeginner» Blog» Tutorials» How to Set, Get, and Delete WordPress Cookies (like a Pro)

How to Set, Get, and Delete WordPress Cookies (like a Pro)

Last updated on March 19th, 2018 by Editorial Staff
141 Shares
Share
Tweet
Share
Pin
Free WordPress Video Tutorials on YouTube by WPBeginner
How to Set, Get, and Delete WordPress Cookies (like a Pro)

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.

How to set, get, and delete cookies in WordPress

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’.

Content settings in Google Chrome

Under content settings, you will need to click on ‘Cookies’ to open the cookies settings page.

Cookies section in Chrome settings

Next, you need to click on the ‘All cookies and site data’ option.

View all cookies and site data

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.

View site cookies

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.

141 Shares
Share
Tweet
Share
Pin
Popular on WPBeginner Right Now!
  • How to Properly Move Your Blog from WordPress.com to WordPress.org

  • Google Analytics in WordPress

    How to Install Google Analytics in WordPress for Beginners

  • How to Fix the Error Establishing a Database Connection in WordPress

    How to Fix the Error Establishing a Database Connection in WordPress

  • Revealed: Why Building an Email List is so Important Today (6 Reasons)

    Revealed: Why Building an Email List is so Important Today (6 Reasons)

About the Editorial Staff

Editorial Staff at WPBeginner is a team of WordPress experts led by Syed Balkhi. Trusted by over 1.3 million readers worldwide.

The Ultimate WordPress Toolkit

13 Comments

Leave a Reply
  1. Nigel says:
    Jan 2, 2021 at 11:58 am

    Thanks for the awesome tutorial!

    A small mistake: In the first code snippet $wpb_visit_time should be ‘wpb_visit_time’

    Reply
    • WPBeginner Support says:
      Jan 4, 2021 at 10:58 am

      Thanks for catching that, we’ll be sure to update the code :)

      Reply
  2. Matt says:
    Oct 14, 2020 at 6:22 am

    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.

    Reply
    • WPBeginner Support says:
      Oct 14, 2020 at 10:15 am

      Thanks for pointing that out, we will be sure to update and fix that, glad our guides have been useful :)

      Reply
  3. Anastasia says:
    Oct 10, 2020 at 7:59 pm

    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?

    Reply
    • WPBeginner Support says:
      Oct 12, 2020 at 10:59 am

      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.

      Reply
  4. Brian says:
    Jun 3, 2020 at 10:02 am

    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?

    Reply
    • WPBeginner Support says:
      Jun 4, 2020 at 8:38 am

      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/

      Reply
  5. Geeby says:
    Apr 23, 2020 at 11:22 am

    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?

    Reply
    • WPBeginner Support says:
      Apr 24, 2020 at 10:04 am

      You would want to check with the support for your eCommerce plugin for if they have a method to set that for your users.

      Reply
  6. Les says:
    Jan 29, 2019 at 12:14 am

    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.

    Reply
    • WPBeginner Support says:
      Jan 29, 2019 at 11:37 am

      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.

      Reply
    • Anthony Coffey says:
      Apr 18, 2019 at 5:05 pm

      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.

      Reply

Leave a Reply Cancel reply

Thanks for choosing to leave a comment. Please keep in mind that all comments are moderated according to our comment policy, and your email address will NOT be published. Please Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

Over 1,320,000+ Readers

Get fresh content from WPBeginner

Featured WordPress Plugin
MonsterInsights
MonsterInsights
Google Analytics made easy for WordPress. Learn More »
How to Start a Blog How to Start a Blog
I need help with ...
Starting a
Blog
WordPress
Performance
WordPress
Security
WordPress
SEO
WordPress
Errors
Building an
Online Store
Useful WordPress Guides
    • 7 Best WordPress Backup Plugins Compared (Pros and Cons)
    • How to Fix the Error Establishing a Database Connection in WordPress
    • Why You Need a CDN for your WordPress Blog? [Infographic]
    • 30 Legit Ways to Make Money Online Blogging with WordPress
    • Self Hosted WordPress.org vs. Free WordPress.com [Infograph]
    • Free Recording: WordPress Workshop for Beginners
    • 24 Must Have WordPress Plugins for Business Websites
    • How to Properly Move Your Blog from WordPress.com to WordPress.org
    • 5 Best Contact Form Plugins for WordPress Compared
    • Which is the Best WordPress Popup Plugin? (Comparison)
    • Best WooCommerce Hosting in 2020 (Comparison)
    • How to Fix the Internal Server Error in WordPress
    • How to Install WordPress - Complete WordPress Installation Tutorial
    • Why You Should Start Building an Email List Right Away
    • How to Properly Move WordPress to a New Domain Without Losing SEO
    • How to Choose the Best WordPress Hosting for Your Website
    • How to Choose the Best Blogging Platform (Comparison)
    • WordPress Tutorials - 200+ Step by Step WordPress Tutorials
    • 5 Best WordPress Ecommerce Plugins Compared
    • 5 Best WordPress Membership Plugins (Compared)
    • 7 Best Email Marketing Services for Small Business (2020)
    • How to Choose the Best Domain Registrar (Compared)
    • The Truth About Shared WordPress Web Hosting
    • When Do You Really Need Managed WordPress Hosting?
    • 5 Best Drag and Drop WordPress Page Builders Compared
    • How to Switch from Blogger to WordPress without Losing Google Rankings
    • How to Properly Switch From Wix to WordPress (Step by Step)
    • How to Properly Move from Weebly to WordPress (Step by Step)
    • Do You Really Need a VPS? Best WordPress VPS Hosting Compared
    • How to Properly Move from Squarespace to WordPress
    • How to Register a Domain Name (+ tip to get it for FREE)
    • HostGator Review - An Honest Look at Speed & Uptime (2020)
    • SiteGround Reviews from 4196 Users & Our Experts (2020)
    • Bluehost Review from Real Users + Performance Stats (2020)
    • How Much Does It Really Cost to Build a WordPress Website?
    • How to Create an Email Newsletter the RIGHT WAY (Step by Step)
    • Free Business Name Generator (A.I Powered)
    • How to Create a Free Business Email Address in 5 Minutes (Step by Step)
    • How to Install Google Analytics in WordPress for Beginners
    • How to Move WordPress to a New Host or Server With No Downtime
    • Why is WordPress Free? What are the Costs? What is the Catch?
    • How to Make a Website in 2020 – Step by Step Guide
Deals & Coupons (view all)
MainWP
MainWP Coupon
Get 15% OFF on MainWP WordPress multisite manager plugin.
Sprout Invoices
Sprout Invoices Coupon
Get 50% OFF on Sprout Invoices WordPress invoicing plugin.
Featured In
About WPBeginner®

WPBeginner is a free WordPress resource site for Beginners. WPBeginner was founded in July 2009 by Syed Balkhi. The main goal of this site is to provide quality tips, tricks, hacks, and other WordPress resources that allows WordPress beginners to improve their site(s).
Join our team: We are Hiring!

Site Links
  • About Us
  • Contact Us
  • FTC Disclosure
  • Privacy Policy
  • Terms of Service
  • Free Blog Setup
  • Free Business Tools
Our Sites
  • OptinMonster
  • MonsterInsights
  • WPForms
  • SeedProd
  • Nameboy
  • RafflePress
  • Smash Balloon

Copyright © 2009 - 2021 WPBeginner LLC. All Rights Reserved. WPBeginner® is a registered trademark.

Managed by Awesome Motive | WordPress hosting by SiteGround | WordPress CDN by MaxCDN | WordPress Security by Sucuri.