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

In the digital currency market, real-time mastering of Bitcoin prices and transaction in-depth information is a must-have skill for every investor. Viewing accurate K-line charts and depth charts can help judge the power of buying and selling, capture market changes, and improve the scientific nature of investment decisions.

This article lists the top ten trading software in the currency circle, namely: 1. Binance, a world-leading exchange, supports multiple trading modes and financial services, with a friendly interface and high security; 2. OKX, rich products, good user experience, supports multilingual and multiple security protection; 3. gate.io, known for strict review and diversified trading services, attaches importance to community and customer service; 4. Huobi, an old platform, has stable operations, strong liquidity, and has a great brand influence; 5. KuCoin, has large spot trading volume, rich currency, low fees, and diverse functions; 6. Kraken, a US compliance exchange, has strong security, supports leverage and OTC trading; 7. Bitfinex, has a long history, professional tools, suitable for high

Ethereum is a decentralized application platform based on smart contracts, and its native token ETH can be obtained in a variety of ways. 1. Register an account through centralized platforms such as Binance and Ouyiok, complete KYC certification and purchase ETH with stablecoins; 2. Connect to digital storage through decentralized platforms, and directly exchange ETH with stablecoins or other tokens; 3. Participate in network pledge, and you can choose independent pledge (requires 32 ETH), liquid pledge services or one-click pledge on the centralized platform to obtain rewards; 4. Earn ETH by providing services to Web3 projects, completing tasks or obtaining airdrops. It is recommended that beginners start from mainstream centralized platforms, gradually transition to decentralized methods, and always attach importance to asset security and independent research, to

The failure to register a Binance account is mainly caused by regional IP blockade, network abnormalities, KYC authentication failure, account duplication, device compatibility issues and system maintenance. 1. Use unrestricted regional nodes to ensure network stability; 2. Submit clear and complete certificate information and match nationality; 3. Register with unbound email address; 4. Clean the browser cache or replace the device; 5. Avoid maintenance periods and pay attention to the official announcement; 6. After registration, you can immediately enable 2FA, address whitelist and anti-phishing code, which can complete registration within 10 minutes and improve security by more than 90%, and finally build a compliance and security closed loop.

Identifying the trend of the main capital can significantly improve the quality of investment decisions. Its core value lies in trend prediction, support/pressure position verification and sector rotation precursor; 1. Track the net inflow direction, trading ratio imbalance and market price order cluster through large-scale transaction data; 2. Use the on-chain giant whale address to analyze position changes, exchange inflows and position costs; 3. Capture derivative market signals such as futures open contracts, long-short position ratios and liquidated risk zones; in actual combat, trends are confirmed according to the four-step method: technical resonance, exchange flow, derivative indicators and market sentiment extreme value; the main force often adopts a three-step harvesting strategy: sweeping and manufacturing FOMO, KOL collaboratively shouting orders, and short-selling backhand shorting; novices should take risk aversion actions: when the main force's net outflow exceeds $15 million, reduce positions by 50%, and large-scale selling orders

User agent stylesheets are the default CSS styles that browsers automatically apply to ensure that HTML elements that have not added custom styles are still basic readable. They affect the initial appearance of the page, but there are differences between browsers, which may lead to inconsistent display. Developers often solve this problem by resetting or standardizing styles. Use the Developer Tools' Compute or Style panel to view the default styles. Common coverage operations include clearing inner and outer margins, modifying link underscores, adjusting title sizes and unifying button styles. Understanding user agent styles can help improve cross-browser consistency and enable precise layout control.

CSSclamp()enablesresponsivetypographybysettingminimum,preferred,andmaximumvaluesthatscalesmoothlywithoutmediaqueries;forexample,font-size:clamp(1.5rem,2.5vw,3rem)ensurestextisneversmallerthan1.5rem,scaleswithviewportwidthbetweensizes,andcapsat3rem,pr

First, click the official download link provided in the article to complete the application download. 1. Click the official download link marked in green to start downloading the installation package. When the browser prompts for risks, select "Stay to download"; 2. After the download is completed, enter the "Security" or "Privacy" option in the device "Settings" and enable "Allow to install applications from unknown sources", and then click the downloaded installation package to complete the installation according to the prompts; 3. After the installation is successful, open the application, select register a new account or log in to an existing account, complete the registration according to the instructions and properly keep the account information. After logging in, you can use Binance's various digital asset trading and management functions.
