How to set, get and delete WordPress cookies (like a professional)
Do 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









Blockchain browser is a must-have on-chain query tool for Web3 users. 1. It serves as a "search engine" in the decentralized world, allowing users to openly and transparently verify all records on the blockchain; 2. The core functions include querying transaction details, viewing account information, exploring block data and tracking smart contracts; 3. When tracking transactions, you need to obtain the transaction hash, select the browser corresponding to the public chain, and enter the hash to view the status, address, amount and fee details; 4. Confirm whether the transaction is successful through the browser is a key step to ensure the security of digital assets. Proficient use can help users better understand and participate in the blockchain ecosystem, thereby operating more safely and stably in the decentralized world.

Blockchain confirmation time refers to the time it takes for a transaction to be broadcasted to be packaged by a block and written to the chain. The confirmation speeds of different chains vary. 1. Bitcoin produces blocks on average in 10 minutes, and it is recommended to confirm 6 times to ensure security; 2. Ethereum produces blocks in about 12 seconds, and 1-3 times can be confirmed, and most transactions are completed within 1 minute; 3. The BSC chain block time is about 3 seconds, suitable for high-frequency trading; 4. The TRON tide block time is 1-3 seconds, suitable for real-time transfer; 5. The Polygon block time is about 2 seconds, with low fees, and is widely used in DeFi and NFT. Trading hash (TxID) is required for query and confirmation status. Recommended platforms include: 1. Ouyi OKX, which supports multi-chain transaction query; 2. Binance, suitable for BSC chain; 3. Huobi HT

Digital currency is a decentralized electronic currency based on blockchain technology. Its value is determined by market supply and demand. It is globally universal, transparent in transactions and has certain anonymity. 1. Binance is the largest platform in the world with transaction volume, providing rich currencies and a strong ecosystem. 2. OkX has a comprehensive product line, supporting derivatives trading and Web3 accounts, suitable for advanced users; 3. Huobi (Huobi/HTX) has a long history, is safe and stable, and is deeply trusted by old users; 4. Gat

In 2025, the cryptocurrency market will be driven by three major factors: clear policy supervision, in-depth institutional participation and technological innovation. 1. The United States may introduce a comprehensive crypto bill, and global regulatory coordination (such as the EU MiCA) will enhance the legitimacy of the industry; 2. Institutional funds will enter large-scale through compliant products such as Bitcoin and Ethereum ETFs, and exchanges such as Binance, OKX, Huobi, Gate.io and Coinbase will serve as core infrastructure to undertake institutional traffic; 3. The popularization of Layer 2 network will promote the scale of applications, and the tokenization of real-world assets (RWA) is expected to inject trillion-dollar liquidity into DeFi. The integration of AI and crypto will give birth to a new paradigm, jointly driving the growth of the industry's intrinsic value.

After experiencing the collapse of algorithmic stablecoins and stricter regulation, the US dollar stablecoin supported by fiat currency reserves has become the biggest winner in the market due to its high transparency and strong compliance, and its dominance has been consolidated. 1. Tether (USDT) has become the core trading pair of mainstream exchanges around the world such as Binance, Ouyi and Huobi with its maximum market value and extensive liquidity; 2. USD Coin (USDC) has won the favor of institutions for its high transparency and regular audits, and has widely supported it on platforms such as Binance, Ouyi and Coinbase; 3. First Digital USD (FDUSD) is an emerging compliant stablecoin, which has developed rapidly under the promotion of Binance and has gradually entered platforms such as Gate.io; 4. Dai (DA

Public keys are used to receive assets and identity identification, private keys are used to sign and control assets. The two are based on asymmetric encryption technologies such as ECDSA. Private keys can be derived from public keys but vice versa. mainstream platforms such as Ouyi OKX adopts multiple signatures and cold storage, Binance uses hardware isolation and layered permissions, Huobi HTX implements hot and cold separation and whitelisting mechanisms, and Gate.io gate combines multiple signatures and distributed storage; public keys and private keys are used in blockchain for identity authentication, asset control and decentralized login; key security management suggestions include offline backup, anti-phishing, enabling multi-factor authentication and using multi-signature or MPC; among different management methods, single keys are at high risk, multiple signatures are suitable for teams, and hardware equipment is highly secure but costly.

Binance provides comprehensive market and trading, with fast official website and app data and wide coverage; 2. OkX market tools are powerful, supporting spot and futures and other multi-product data; 3. Huobi (HTX) has stable data and simple interface, suitable for novices; 4. Gate.io has rich currency, which is conducive to tracking niche projects; 5. CoinMarketCap is an authoritative data aggregation platform, providing market value ranking and macro analysis; 6. CoinGecko is neutral and comprehensive, and includes fast new coins and provides community and developer indicators; 7. TradingView is a benchmark for technical analysis, integrating multi-exchange data, powerful chart functions, and all have free web pages and app versions for use.

The top ten virtual currency exchanges in the world in 2025 are: 1. Binance, which ranks first with its leading trading volume, rich currency and complete ecosystem; 2. OKX, which ranks second with strong derivatives trading and Web3 account technology; 3. Coinbase, as a Nasdaq listed platform, is known for its high compliance and novice friendly; 4. Kraken, has a long history, high security, and has complete fiat currency support; 5. Gate.io, which is famous for its massive altcoins and fast new projects; 6. KuCoin, which is active in the community, focuses on the functions of new currency initial public offerings and trading robots; 7. Huobi (HTX), which has a deep user base, continuously optimizes services and revitalizes market position; 8. By
