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)

We once faced a frustrating issue where user logins and shopping carts on one of our sites kept failing. The hidden culprit was a simple oversight in how our site managed cookies.

Dealing with technical settings like cookies can feel intimidating for beginners. However, getting this right is the secret to a fast, user-friendly website.

After fixing our own errors, we developed a straightforward system that anyone can follow. We will walk you through the exact methods we use to handle cookies safely.

In this guide, we will show you how to easily set, get, and delete cookies in WordPress. Let’s look at the exact steps so you can manage your site’s data with confidence.

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

Here are the topics we cover in this article:

Note: While this tutorial involves some custom code, don’t worry. We will walk you through each step. We recommend using a code snippet plugin so you don’t need to be a PHP expert to follow along.

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

While cookies are powerful tools for website owners, they can raise privacy concerns. Modern marketing practices, including email marketing, growth hacking, and digital advertising, often use cookies as tracking beacons to collect and share user activity across multiple websites.

Because cookies can track what users do, many countries have strict privacy laws. For example, laws like the GDPR require you to ask visitors for permission before you save most types of cookies on their devices.

WPConsent makes it easy to add a fully compliant cookie consent system to your WordPress site. This plugin goes beyond basic notifications by actively blocking tracking scripts until visitors give their permission.

Cookies popup created with WPConsent

Creating a cookie consent banner with WPConsent is simple. You can choose a pre-made template, customize the design to match your site, and let the plugin automatically handle all visitor consent management for you.

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.

Site settings in Google Chrome

On the Settings page, click on ‘Privacy and security’ in the left-hand menu.

Next, under ‘Privacy and security,’ look for and click on ‘Third-party cookies’.

Cookies section in Chrome settings

This will open the cookies settings page.

Next, you need to click on the ‘See all site data and permissions’ 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.

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. Sets a time limit for the cookie to remain active before it deletes itself.
  • Path – optional. It will use your site’s root path by default.
  • Domain – optional. It uses your website’s main domain name by default.
  • Secure – optional. When set to true, this ensures the cookie only works if your website has an active SSL certificate (HTTPS).
  • httponly – optional. When set to true, the cookie is hidden from JavaScript, which helps protect your site from malicious 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);
  }
}
add_action('init', 'wpb_cookies_tutorial1');

In this code, we set the expiration time using time() + 31556926. The time() function represents the current exact moment, and the large number is exactly how many seconds are in one year (60 times 60 times 24 times 365.25).

You can now visit your website and then check your browser cookies. You will find a cookie with the name wpb_visit_time.

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. Because cookies are sent through HTTP headers, we have to use the init hook to set the cookie before any HTML is loaded on the page.

Let’s add some code that not only sets the cookie but also creates a shortcode to display a message on your website:

// 1. Set the cookie during WordPress init
function wpb_set_visit_cookie() {
    if ( ! isset( $_COOKIE['wpb_visit_time'] ) ) {
        $visit_time = date( 'F j, Y g:i a' );
        // Set a cookie for 1 year
        setcookie( 'wpb_visit_time', $visit_time, time() + 31556926 );
    }
}
add_action( 'init', 'wpb_set_visit_cookie' );

// 2. Create the shortcode to display the message
function wpb_visitor_greeting_shortcode() {
    if ( isset( $_COOKIE['wpb_visit_time'] ) ) {
        // Always escape cookie data for security!
        $lastvisit = esc_html( $_COOKIE['wpb_visit_time'] );
        $message = 'You last visited our website on ' . $lastvisit . '. Check out whats new!';
    } else {
        $message = 'New here? Check out these resources...';
    }
    return $message;
}
add_shortcode( 'greet_me', 'wpb_visitor_greeting_shortcode' );

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.

Pro Tip: If the shortcode doesn’t seem to update the time, your WordPress caching plugin might be caching an old, static version of the page. You may need to exclude the page containing this shortcode from your cache settings to see it update live.

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.

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 from a user’s browser, you need to use the setcookie() function and set the expiration date to the past. You can add the following line to your code:

setcookie( 'wpb_visit_time', '', time() - 3600 );

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:

// 1. Manage the cookie (Read old, Delete, Set new)
function wpb_update_visit_cookie() {
    $current_time = date( 'F j, Y g:i a' );

    // Check if cookie is already set
    if ( isset( $_COOKIE['wpb_visit_time'] ) ) {
        // Save the old time so our shortcode can still display it on this page load
        $GLOBALS['last_visit'] = $_COOKIE['wpb_visit_time'];

        // Delete the old browser cookie by setting the time to the past
        setcookie( 'wpb_visit_time', '', time() - 3600 );
    }

    // Set the cookie again with the newly updated time
    setcookie( 'wpb_visit_time', $current_time, time() + 31556926 );
}

add_action( 'init', 'wpb_update_visit_cookie' );

// 2. Create the shortcode to display the message
function wpb_greeting_shortcode() {
    // Look for the saved global variable first
    if ( isset( $GLOBALS['last_visit'] ) ) {
        $lastvisit = esc_html( $GLOBALS['last_visit'] );
        $message = 'You last visited our website on ' . $lastvisit . '. Check out whats new!';
    } else {
        $message = 'New here? Check out these resources...';
    }
    return $message;
}
add_shortcode( 'greet_me', 'wpb_greeting_shortcode' );

As you can see, this code deletes the specific browser cookie we created by setting the timer to the past.

Don’t worry, this only removes your site’s specific cookie and does not clear the user’s entire browser cache or history. Then, we set the cookie again with the newly updated time information.

Pro Tip: If you are trying to delete a cookie and it isn’t working, make sure your path and domain parameters exactly match the ones you used when you first created the cookie!

Frequently Asked Questions About WordPress Cookies

Here are the answers to some of the most common questions about setting, getting, and deleting cookies in WordPress.

1. What are website cookies?

Website cookies are small text files stored in a visitor’s web browser. They are used to save and retrieve information for a specific website, such as remembering a user’s login status, keeping items in a shopping cart, or personalizing their experience.

2. Are WordPress cookies bad for my site?

No, cookies are not inherently bad. They are essential for many core WordPress functions like managing user logins and remembering commenter information. However, because they can track user activity, they raise privacy concerns, which is why regulations like GDPR exist.

3. Do I need to show a cookie consent notice in WordPress?

If your website has visitors from countries with privacy laws like the European Union’s GDPR, then you are required to get user consent before storing most types of cookies. Using a plugin like WPConsent is an easy way to ensure compliance.

4. How can I see which cookies my website is using?

You can view all cookies a website uses directly in your browser’s developer tools or settings. For example, in Google Chrome, you can go to Settings » Privacy and security » Third-party cookies and then click ‘See all site data and permissions’ to inspect the cookies for any site you’ve visited.

Additional Resources 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.

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. Hello, I did not understand whether to put the file in the theme folder in the functions. file and save it

  2. 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);

  3. 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. Thanks for the awesome tutorial!

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

  5. 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 :)

      Admin

  6. 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?

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

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

      Admin

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

      Admin

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