search
HomeCMS TutorialWordPressHow 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.

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.

How to set, get and delete WordPress cookies (like a professional)

On the Settings page, you need to search for Content Settings.

Under "Content Settings", you need to click "Cookies".

How to set, get and delete WordPress cookies (like a professional)

This will open the cookie settings page.

Next, you need to click on the "View all cookies and site data" option.

How to set, get and delete WordPress cookies (like a professional)

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.

How to set, get and delete WordPress cookies (like a professional)

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.

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!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Is WordPress suitable for e-commerce?Is WordPress suitable for e-commerce?May 13, 2025 am 12:05 AM

Yes, WordPress is very suitable for e-commerce. 1) With the WooCommerce plugin, WordPress can quickly become a fully functional online store. 2) Pay attention to performance optimization and security, and regular updates and use of caches and security plug-ins are the key. 3) WordPress provides a wealth of customization options to improve user experience and significantly optimize SEO.

How to add your WordPress site in Yandex Webmaster ToolsHow to add your WordPress site in Yandex Webmaster ToolsMay 12, 2025 pm 09:06 PM

Do you want to connect your website to Yandex Webmaster Tools? Webmaster tools such as Google Search Console, Bing and Yandex can help you optimize your website, monitor traffic, manage robots.txt, check for website errors, and more. In this article, we will share how to add your WordPress website to the Yandex Webmaster Tool to monitor your search engine traffic. What is Yandex? Yandex is a popular search engine based in Russia, similar to Google and Bing. You can excel in Yandex

How to fix HTTP image upload errors in WordPress (simple)How to fix HTTP image upload errors in WordPress (simple)May 12, 2025 pm 09:03 PM

Do you need to fix HTTP image upload errors in WordPress? This error can be particularly frustrating when you create content in WordPress. This usually happens when you upload images or other files to your CMS using the built-in WordPress media library. In this article, we will show you how to easily fix HTTP image upload errors in WordPress. What is the reason for HTTP errors during WordPress media uploading? When you try to upload files to Wo using WordPress media uploader

How to fix the issue where adding media buttons don't work in WordPressHow to fix the issue where adding media buttons don't work in WordPressMay 12, 2025 pm 09:00 PM

Recently, one of our readers reported that the Add Media button on their WordPress site suddenly stopped working. This classic editor problem does not show any errors or warnings, which makes the user unaware why their "Add Media" button does not work. In this article, we will show you how to easily fix the Add Media button in WordPress that doesn't work. What causes WordPress "Add Media" button to stop working? If you are still using the old classic WordPress editor, the Add Media button allows you to insert images, videos, and more into your blog post.

How to set, get and delete WordPress cookies (like a professional)How to set, get and delete WordPress cookies (like a professional)May 12, 2025 pm 08:57 PM

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 WordPresscookies 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 created and stored when users visit websites.

How to Fix WordPress 429 Too Many Request ErrorsHow to Fix WordPress 429 Too Many Request ErrorsMay 12, 2025 pm 08:54 PM

Do you see the "429 too many requests" error on your WordPress website? This error message means that the user is sending too many HTTP requests to the server of your website. This error can be very frustrating because it is difficult to find out what causes the error. In this article, we will show you how to easily fix the "WordPress429TooManyRequests" error. What causes too many requests for WordPress429? The most common cause of the "429TooManyRequests" error is that the user, bot, or script attempts to go to the website

How scalable is WordPress as a CMS for large websites?How scalable is WordPress as a CMS for large websites?May 12, 2025 am 12:08 AM

WordPresscanhandlelargewebsiteswithcarefulplanningandoptimization.1)Usecachingtoreduceserverload.2)Optimizeyourdatabaseregularly.3)ImplementaCDNtodistributecontent.4)Vetpluginsandthemestoavoidconflicts.5)ConsidermanagedWordPresshostingforenhancedperf

How customizable is WordPress, really?How customizable is WordPress, really?May 11, 2025 am 12:11 AM

WordPress is very customized, providing a wide range of flexibility and customizability. 1) Through the theme and plug-in ecosystem, 2) use RESTAPI for front-end development, 3) In-depth code level modifications, users can achieve a highly personalized experience. However, customization requires mastering technologies such as PHP, JavaScript, CSS, etc., and pay attention to performance optimization and plug-in selection to avoid potential problems.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Article

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.