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 cryptocurrency market in 2025 is still full of opportunities, and choosing a suitable app is the first step to success. Before making a decision, it is recommended that users comprehensively consider their trading experience, product types of interest, and preferences for functional complexity. Most importantly, no matter which platform you choose, asset security should be put first and always maintain a learning mindset to adapt to this rapidly changing market.

There is no legal virtual currency platform in mainland China. 1. According to the notice issued by the People's Bank of China and other departments, all business activities related to virtual currency in the country are illegal; 2. Users should pay attention to the compliance and reliability of the platform, such as holding a mainstream national regulatory license, having a strong security technology and risk control system, an open and transparent operation history, a clear asset reserve certificate and a good market reputation; 3. The relationship between the user and the platform is between the service provider and the user, and based on the user agreement, it clarifies the rights and obligations of both parties, fee standards, risk warnings, account management and dispute resolution methods; 4. The platform mainly plays the role of a transaction matcher, asset custodian and information service provider, and does not assume investment responsibilities; 5. Be sure to read the user agreement carefully before using the platform to enhance yourself

The rise of meme coins reflects the key role of community power and social media influence in the cryptocurrency market. 1. Dogecoin was originally a satirical joke and was born in 2013; 2. Driven by tweets from celebrities such as Elon Musk, the attention soared; 3. The market value once reached tens of billions of dollars, becoming a mainstream digital asset. Shiba Inu Coin is positioned as a "dogcoin killer" and has rapidly risen through community-driven strategies, building a decentralized exchange ShibaSwap, and relies on low-priced units to attract a large number of users to participate. Its success also depends on circulation guarantees on mainstream platforms such as Binance, Coinbase, and OKX. The core driving forces of meme coins include: 1. Viral transmission mechanism, rapid spread of information; 2. Enhanced sense of community belonging

Bitcoin halving affects the price of currency through four aspects: enhancing scarcity, pushing up production costs, stimulating market psychological expectations and changing supply and demand relationships; 1. Enhanced scarcity: halving reduces the supply of new currency and increases the value of scarcity; 2. Increased production costs: miners' income decreases, and higher coin prices need to maintain operation; 3. Market psychological expectations: Bull market expectations are formed before halving, attracting capital inflows; 4. Change in supply and demand relationship: When demand is stable or growing, supply and demand push up prices.

The acquisition and management of digital assets can be achieved through the official Solana platform and secure storage solutions. 1. Solana's official application platform (solana.com/ecosystem) provides project browsing, official application downloads and developer resources; 2. Its trading platform address is a designated link to facilitate user transactions; 3. Hardware storage devices such as Ledger can ensure private key security offline; 4. Desktop or mobile applications such as Phantom support convenient management; 5. Multi-signature technology improves authorization security; in addition, you can also participate in the digital asset ecosystem by participating in community governance, using decentralized applications, content creation, etc.

Cardano's Alonzo hard fork upgrade has successfully transformed Cardano from a value transfer network to a fully functional smart contract platform by introducing the Plutus smart contract platform. 1. Plutus is based on Haskell language, with powerful functionality, enhanced security and predictable cost model; 2. After the upgrade, dApps deployment is accelerated, the developer community is expanded, and the DeFi and NFT ecosystems are developing rapidly; 3. Looking ahead to 2025, the Cardano ecosystem will be more mature and diverse. Combined with the improvement of scalability in the Basho era, the enhancement of cross-chain interoperability, the evolution of decentralized governance in the Voltaire era, and the promotion of mainstream adoption by enterprise-level applications, Cardano has

The pattern in the public chain field shows a trend of "one super, many strong ones, and a hundred flowers blooming". Ethereum is still leading with its ecological moat, while Solana, Avalanche and others are challenging performance. Meanwhile, Polkadot, Cosmos, which focuses on interoperability, and Chainlink, which is a critical infrastructure, form a future picture of multiple chains coexisting. For users and developers, choosing which platform is no longer a single choice, but requires a trade-off between performance, cost, security and ecological maturity based on specific needs.

The latest price of Dogecoin can be queried in real time through a variety of mainstream APPs and platforms. It is recommended to use stable and fully functional APPs such as Binance, OKX, Huobi, etc., to support real-time price updates and transaction operations; mainstream platforms such as Binance, OKX, Huobi, Gate.io and Bitget also provide authoritative data portals, covering multiple transaction pairs and having professional analysis tools. It is recommended to obtain information through official and well-known platforms to ensure data accuracy and security.
