How to set, get and delete WordPress cookies (like a professional)
May 12, 2025 pm 08:57 PMDo you want to know how to use cookies on your WordPress website?
Cookies are useful tools for storing temporary information in users' browsers. You can use this information to enhance the 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 professional.
Note: This is an advanced tutorial. It requires you to be proficient in HTML, CSS, WordPress websites and PHP.
What are cookies?
Cookies are plain text files created and stored in the user's browser when a user visits a website. You can use cookies to add different features to your WordPress website.
Here are some common use cases for cookies:
- Store and manage user login information
- Store temporary session information during user access
- Remember shopping cart merchandise during user visits e-commerce stores
- Track user activity on the website to provide a personalized user experience
As you can see, cookies are a very useful tool for website owners, but can also be somewhat intrusive. The latest trends in email marketing, growth hacking and online marketing allow websites to set cookies, act as beacons, and can be used to save and even share user activity across websites.
This is why the EU enacts the EU Cookie Act, which requires website owners to declare that they use cookies to store information.
You can learn how to do this on your own website in our guide on how to add cookies to GDPR/CCPA.
How to use cookies on a typical WordPress website
By default, WordPress uses cookies to manage logged-in user sessions and authentication, and remembers the user's name and email address as the user fills out the comment form.
However, many WordPress plugins on your website may also set their own cookies.
For example, OptinMonster allows you to display different email selection forms to new visitors and return visitors, which is achieved by using cookies.
If you use external web services on your website, such as 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 settings. For example, in Google Chrome, you need to first open the Settings page.
You can do this by clicking the 3 dots icon in the upper right corner and selecting Settings or chrome://settings in the address bar.
On the Settings page, you need to search for Content Settings.
Under "Content Settings", you need to click "Cookies".
This will open the cookie settings page.
Next, you need to click on the "View all cookies and site data" option.
On the next page, you will see a list of all cookies and website data stored on your browser for all websites you visited.
You can enter the website address in the search box and you will see the data stored on the website.
Clicking on a single item will show you more detailed information about individual cookies and their content.
How to set cookies in WordPress
To learn this tutorial, you need to add the code to the functions.php file of the topic or use a code snippet plugin such as WPCode. If you haven't done this before, check out our guide on how to copy and paste code snippets in WordPress.
First, we will use the function in PHPsetcookie(). This function accepts the following parameters:
- Cookie name
- Cookie value
- Expiration – Optionally, set the time period for which the cookie expires
- Path – Optional, using the root directory of the site by default
- Domain name – optional, the domain name of your website is used by default
- Security – Optional, if true, cookie data is transmitted only over HTTPS
- httponly – Optional, when set to true, cookies can only be accessed via HTTP and cannot be used by scripts
Now, let's add code snippets to your WordPress site. This code stores the exact timestamp of a user's visit to your website in a cookie:
functionwpb_cookies_tutorial1() { $visit_time= date('F j, Y g:i a');if(!isset($_COOKIE[wpb_visit_time])) {// set a cookie for 1 yearsetcookie('wpb_visit_time', $visit_time, time() 31556926);}}
Depend on
Use it with one click in WordPress
You can now visit your website and then check your browser cookies. You will find a cookie called wpb_visit_time.
How to get a cookie and use it in WordPress
Now that we have created this cookie, it will be stored in the user's browser for a year, let's see how this information is used on our website.
If you know the name of the cookie, you can easily call it anywhere in PHP using the $_COOKIE[] variable. Let's add some code that not only sets cookies, but also uses it to do something on your website:
functionwpb_cookies_tutorial2() {// Time of user's visit$visit_time= date('F j, Y g:i a');// Check if cookie is already setif(isset($_COOKIE['wpb_visit_time'])) {// Do this if cookie is setfunctionvisitor_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 existfunctionvisitor_greeting() {$string.= 'New here? Check out these resources...';return$string;} // Set the cookiessetcookie('wpb_visit_time', $visit_time, time() 31556926);}// Add a shortcodeadd_shortcode('greet_me', 'visit_greeting');}add_action('init', 'wpb_cookies_tutorial2');
Depend on
Use it with one click in WordPress
We have added comments to the code to show you what each section does. This code uses the information stored in the cookie and outputs it using a short code.
You can now add a shortcode [greet_me] anywhere on the website, which will show the last time the user visited.
Feel free to modify the code to make it more useful to your website. For example, you can show recent posts to return users and popular posts to new users.
Delete Cookies in WordPress
So far, we've learned how to set cookies and use it later on your website. Now, let's see how to delete cookies.
To delete a cookie, you need to add the following line to your code:
functionwpb_cookies_tutorial2() {// Time of user's visit$visit_time= date('F j, Y g:i a');// Check if cookie is already setif(isset($_COOKIE['wpb_visit_time'])) {// Do this if cookie is setfunctionvisitor_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 timeunset($_COOKIE['wpb_visit_time']); return$string;} } else{// Do this if the cookie doesn't existfunctionvisitor_greeting() {$string.= 'New here? Check out these resources...';return$string;}}add_shortcode('greet_me', 'visitor_greeting');// Set or Reset the cookiesetcookie('wpb_visit_time', $visit_time, time() 31556926);}add_action('init', 'wpb_cookies_tutorial2');
Depend on
Use it with one click in WordPress
As you can see, this code deletes the cookie once we use the information stored there. We then set cookies again using the updated time information.
We hope this article helps you understand how to easily set, get, and delete WordPress cookies. You may also want to check out our guide on common WordPress errors and how to fix them, as well as the best analytical solutions that our experts have selected for WordPress users.
The above is the detailed content of How to set, get and delete WordPress cookies (like a professional). For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

The Virtual Currency Exchange APP is a professional digital asset trading application, providing users with safe and convenient digital currency trading services. The new v6.129.0 version has upgraded the performance and operation experience, aiming to bring a smoother trading experience.

Airdrops in the cryptocurrency field are a marketing promotion method for the project to distribute a certain number of tokens for free to community members or potential users. In this way, the project party hopes to increase the visibility of the tokens and attract more users to participate in the project, thereby expanding the size of the community and increasing the liquidity of the tokens. For users, airdrops provide opportunities to obtain project tokens without initial investment, and are one of the ways to get in touch with and understand new projects in the early stage.

Currency circle contract trading is a derivative trading method that uses a small amount of funds to control assets with larger value. It allows traders to speculate on the price trends of crypto assets without actually owning them. Entering the contract market requires understanding its basic operations and related concepts.

The Virtual Digital Coin Exchange APP is a powerful digital asset trading tool, committed to providing safe, professional and convenient trading services to global users. The platform supports a variety of mainstream and emerging digital asset transactions, with a bank-level security protection system and a smooth operating experience.

As an investment method, the currency circle contract order has attracted many investors who want to participate in cryptocurrency contract trading but do not have sufficient time and expertise. The basic principle is to associate your trading account with the outstanding trader's account selected on the platform, and the system will automatically synchronize the trader's opening and closing operation. The user does not need to manually analyze the market and execute the transaction, and the follower is done by the trader. This model seems to simplify the trading process, but it is accompanied by a series of issues that require careful consideration.

How do novice users choose a safe and reliable stablecoin platform? This article recommends the Top 10 stablecoin platforms in 2025, including Binance, OKX, Bybit, Gate.io, HTX, KuCoin, MEXC, Bitget, CoinEx and ProBit, and compares and analyzes them from dimensions such as security, stablecoin types, liquidity, user experience, fee structure and additional functions. The data comes from CoinGecko, DefiLlama and community evaluation. It is recommended that novices choose platforms that are highly compliant, easy to operate and support Chinese, such as KuCoin and CoinEx, and gradually build confidence through a small number of tests.

Bitcoin contract trading attracts numerous participants, which provides opportunities to leverage for potentially high returns. However, the inherent risk of contract trading lies in forced closing of positions, commonly known as "losing of positions". A liquidation means that the trader's position is forced to close due to the loss of margin, which often loses most or even all of the initial margin. Understanding how to set up a liquidation warning and mastering skills to avoid forced liquidation is crucial to managing contract trading risks.

The latest official version of the virtual currency trading platform v6.129.0 is a professional and secure digital asset trading application created for Android users. It provides rich market conditions, convenient trading functions and multiple security protection, and is committed to providing users with a first-class trading experience.
