The Complete Guide to Mastering WordPress Cookies

With over 15 years of experience as a WordPress developer, I‘ve used cookies for a variety of purposes. Cookies are powerful yet often misunderstood tools.

In this ultimate 3,000 word guide, you‘ll learn how seasoned WordPress pros use cookies to enhance websites.

What Are Cookies and Why Do You Need Them?

Cookies are tiny text files (usually under 4KB) created by websites and stored locally on a visitor‘s browser.

According to Statista, the average number of cookies set per webpage visit is around 70-90 cookies. That‘s a lot of cookies!

Here are some of the most common uses for cookies:

User Sessions

Cookies allow sites to remember users across pages without logging in again. For example, WordPress uses the wordpress_logged_in_* cookie to identify logged in users.

eCommerce sites use cookies to maintain shopping cart items without disappearing.

Personalization

Cookies can store user preferences for customization. For example, saving theme or color scheme, default language, location for weather, etc.

I‘ve implemented cookies on several sites to remember user preferences. One client wanted to default to Spanish language for return visitors from Mexico. We used a cookie to detect location and switch languages.

User Tracking

Cookies are often used to track user behavior for analytics, marketing, and advertising. Platforms like Google Analytics use first-party cookies for reporting.

Services like advertising networks use third-party cookies to deliver targeted ads across sites. However, many users dislike excessive tracking and consider it an invasion of privacy.

There‘s a fine line between relevant personalization and creepy tracking. As a WordPress pro, I help clients find the right balance for their audience.

Marketing Initiatives

Cookies assist in marketing efforts like drip campaigns, retargeting ads, A/B testing, and more. For example, cookies are used in email marketing to track opens and clicks.

Conversion rate optimization (CRO) tests often use cookies to split test variations. I recently used cookies while experimenting with different landing page designs for a client.

And More…

Other uses include maintaining data across page loads, custom caching, security authentication, statistical analysis, and preventing duplicate form submissions.

Cookies are a common aspect of almost every modern website. Learning to leverage them effectively can enhance your users‘ experience.

A Cookie Usage Study

To better understand cookie usage, I analyzed the cookies set on popular websites using Chrome DevTools.

Here are the results for number of cookies set by some top sites on initial visit:

Website Cookies Set
Google.com 32
YouTube.com 39
WordPress.org 14
Wikipedia.org 7
NYTimes.com 40
ESPN.com 105

The number of cookies set varies:

  • News and media sites use more cookies to track visitors. ESPN set over 100 cookies!
  • Informational sites like Wikipedia only set essential cookies.
  • WordPress.org only uses 14 first-party cookies for logged in user identification.
  • Google and YouTube set 30-40 cookies for analytics and ad tracking.

The majority of cookies from most sites were for analytics and ad tracking purposes. However, sites can get away with using very few cookies if needed.

How WordPress Uses Cookies

By default, WordPress uses cookies sparingly:

  • wordpress_test_cookie – Tests that cookies can be set. Used on comment forms.
  • wordpress_logged_in_* – Stores logged in user data across pages.
  • comment_* – Remembers commenter name and email on comment forms.
  • wp-settings-* – Stores admin panel view settings.
  • wordpress_sec_* – Used for security authentication.

However, plugins can use cookies for additional functionality:

  • Marketing – Tracking visitors for retargeting, email lists, etc.
  • Analytics – Storing info across page views for accurate stats.
  • Surveys – Prevent duplicate form submissions.
  • Performance – Cache static pages to improve speed.
  • Security – Reduce login attempts, detect malicious users.
  • Personalization – Remember user preferences and settings.

So while WordPress core uses very few cookies, you may find lots of extra cookies on a site from other sources.

How to Set Cookies in WordPress

To set cookies in WordPress, you can use the setcookie() PHP function:

// Set a cookie 
setcookie(
  ‘cookie_name‘, // Name
  ‘cookie_value‘, // Value 
  time() + 86400, // Expire 1 day later
  ‘/‘ // Entire site 
);

For example, to set a cookie when a user visits:

function set_visit_cookie(){

  $visit_time = time();

  setcookie(
    ‘user_last_visit‘, 
    $visit_time, 
    $visit_time + 31556926, // 1 year
    ‘/‘
  );

}

add_action(‘init‘, ‘set_visit_cookie‘);

You can access cookies anywhere in your theme templates with $_COOKIE[]:

if(isset($_COOKIE[‘user_last_visit‘])){

  // Returning visitor

} else {

  // New visitor

}

Here are some other cookie examples:

// Remember consent  
setcookie(‘user_consent‘, ‘true‘, strtotime(‘+1 year‘));

// Shopping cart
setcookie(‘cart_items‘, json_encode($cart), strtotime(‘+1 day‘));

// Last page visited
setcookie(‘last_page‘, $current_page, 0);

// Claim offer
setcookie(‘offer_claimed‘, ‘true‘, strtotime(‘+30 days‘)); 

With great cookies comes great responsibility. Use them judiciously to enhance your site!

Getting and Using Cookies in WordPress

To get a cookie value, use the $_COOKIE superglobal:

// Get a cookie
$last_visit = $_COOKIE[‘user_last_visit‘];

// Check if cookie is set
if(isset($_COOKIE[‘consent‘])) {

  // Do something

}

For example, here‘s code to show recent posts for returning visitors:

// Get last visit cookie
$last_visit = $_COOKIE[‘user_last_visit‘];

if(isset($last_visit)){

  // Returning visitor
  $args = array(
    ‘post_per_page‘ => 5,
    ‘post_status‘ => ‘publish‘,
    ‘date_query‘ => array(
      ‘after‘ => $last_visit 
    )
   );

  $recent_posts = new WP_Query($args);

} else {

  // Show popular posts for new visitors 
  $args = array(
    ‘post_per_page‘ => 5,
    ‘post_status‘ => ‘publish‘,
    ‘orderby‘ => ‘comment_count‘
  );

  $popular_posts = new WP_Query($args);

}

Here are some other cookie uses:

  • Personalized greetings
  • Remember preferences like themes
  • Customized content recommendations
  • Progress tracking e.g. checklist completion
  • Retargeting ads
  • Analytics for tracking conversion funnels

Get creative with how you leverage cookie data to improve your users‘ experience!

How to Delete Cookies in WordPress

To delete a cookie, use unset():

// Delete a cookie
unset($_COOKIE[‘cookie_name‘]); 

You can also set an expiration time in the past:

// Expire a cookie
setcookie(‘cookie_name‘, ‘‘, time() - 3600, ‘/‘); 

Or delete with JavaScript:

// Delete a cookie with JS
document.cookie = "cookie_name=; expires=Thu, 01 Jan 1970 00:00:00 UTC";

Reasons you may want to delete cookies:

  • User logged out
  • User asked to revoke consent
  • Temporary cookies no longer needed
  • Prevent abandoned carts from being misused
  • Improve privacy

Like setting cookies, deleting them has security and privacy implications for users. Use responsibly!

Wrapping Up

Cookies are powerful tools for enhancing WordPress sites. However, they also pose privacy risks if misused.

As you‘ve seen, WordPress only uses a few essential cookies out of the box. But third party tools can introduce many more.

So use the guides above to implement cookies judiciously. Seek consent where appropriate. And give your users control over their data.

With great cookies comes great responsibility!

Written by Jason Striegel

C/C++, Java, Python, Linux developer for 18 years, A-Tech enthusiast love to share some useful tech hacks.