Trusted WordPress tutorials, when you need them most.
Beginner’s Guide to WordPress
WPB Cup
25 Million+
Websites using our plugins
16+
Years of WordPress experience
3000+
WordPress tutorials
by experts

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

Cookies are small files that websites use to remember information about visitors. We use cookies on our own websites to make them more user-friendly and personalized.

Many website owners want to use cookies but are unsure how to start. Cookies can help you remember user preferences, keep people logged in, and even show targeted content.

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 a proficient understanding of HTML, CSS, WordPress sites, and PHP.

What Are Cookies?

Cookies are plain text files that are created and stored in the users’ browsers when they visit a website. You can use cookies to add different features to your WordPress website.

Here are some common use cases for cookies:

  • Storing and managing a user’s login information
  • Storing temporary session information during a user’s visit
  • Remembering cart items during a user’s visit to an eCommerce store
  • Tracking user activity on a site to offer a personalized user experience

As you can see, cookies are a highly useful tool for website owners but 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 save and even share user activity across websites.

This is why the European Union enacted the EU Cookie Law, which requires website owners to declare that they use cookies to store information.

You can learn how to do this on your own site in our guide on how to add a cookies popup for GDPR/CCPA.

How Cookies Are Used on a Typical WordPress Website

By default, WordPress uses cookies to manage logged-in user sessions and authentication and 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 external web services on your website, like Google Analytics or Google AdSense, then they may also set third-party cookies on your website.

You can view all website cookies in your browser’s settings. For example, in Google Chrome, you need to start by opening the Settings page.

You can do this by clicking the ‘3 dots’ icon at the top right and selecting ‘Settings’ or by typing chrome://settings into the address bar.

Content settings in Google Chrome

On the Settings page, you need to search for ‘Content settings’.

Under ‘Content settings’, you will need to click on ‘Cookies’.

Cookies section in Chrome settings

This will open the cookies settings page.

Next, you need to click on the ‘See 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 have visited.

You can type a website address in the search box, and you will be shown 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 use a code snippet plugin such as WPCode. 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 and sets a time period after which the cookie expires
  • Path – optional and will use the site’s root by default
  • Domain – optional and uses your website’s domain by default
  • Secure – optional, and only transfers cookie data via HTTPS if true
  • httponly – optional, and when set to 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 the user’s browser for one year, let’s look at how we can 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 within the code to show you what each part does. This code uses the information stored in the cookie and outputs it using shortcode.

You can now add the 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 on your website. Now, let’s take a look at how to delete cookies.

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.

Expert Guides on Using Cookies With WordPress

We hope this article helped you learn how to easily set, get, and delete WordPress cookies. You may also want to see some other guides related to using cookies in WordPress:

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.

Disclosure: Our content is reader-supported. This means if you click on some of our links, then we may earn a commission. See how WPBeginner is funded, why it matters, and how you can support us. Here's our editorial process.

Editorial Staff

Editorial Staff at WPBeginner is a team of WordPress experts led by Syed Balkhi with over 16 years of experience in WordPress, Web Hosting, eCommerce, SEO, and Marketing. Started in 2009, WPBeginner is now the largest free WordPress resource site in the industry and is often referred to as the Wikipedia for WordPress.

The Ultimate WordPress Toolkit

Get FREE access to our toolkit - a collection of WordPress related products and resources that every professional should have!

Reader Interactions

20 CommentsLeave a Reply

  1. Alex

    Hello, I did not understand whether to put the file in the theme folder in the functions. file and save it

  2. Alan Brady

    A very useful and informative article, thank you.
    I found that just using unset didn’t seem to delete the cookie, I had to set the cookie expiry time to sometime in the past, e.g.:
    setcookie(‘wpb_visit_time’, $visit_time, time()-1);

    • WPBeginner Support

      Thank you for sharing that for those who may run into that issue as well.

      Admin

  3. Debbie Kurth

    Problem is, when I implement code like this, I get an warning error and the cookie fails, when in wordpress.

    Warning: Cannot modify header information – headers already sent by (output started

    How do you go around that?

  4. Pete

    How can I use a cookie to restrict users visit a page just once.

  5. Nigel

    Thanks for the awesome tutorial!

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

    • WPBeginner Support

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

      Admin

  6. Matt

    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.

    • WPBeginner Support

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

      Admin

  7. Anastasia

    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?

  8. Brian

    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?

  9. Geeby

    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?

    • WPBeginner Support

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

      Admin

  10. Les

    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.

    • WPBeginner Support

      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.

      Admin

    • Anthony Coffey

      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.

Leave A 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.