Cookies can be a great way to temporarily store information in a user’s browser. This information can then be used to enhance their user experience with personalisation and behavioural targeting. Here, we are taking you through the ways in which you can set, get and delete cookies in WordPress.
What Exactly Are Cookies?
Cookies are simply plain text files. They are stored in a person’s browser upon visiting your website and this will add different features to the website. Cookies are commonly used for a variety of different reasons. This includes storing and managing login information, storing temporary session information, remembering cart items on an ecommerce website, tracking user activity to offer a user experience that is personalised and much, much more! They are extremely useful to anyone who owns a website, just remember to declare that you are using cookies to store information on your website has to be done through the EU Cookie Law.
Setting a Cookie in WordPress
The first thing that you will be required to do is add the code to the theme’s functions.php file. This could also be a site-specific plugin. You can use the setcookie() function in PHP. It accepts parameters including cookie name and cookie value plus other optional parameters such as expire, path, domain, secure and http only.
You can then add code snippet to the site and this will store the timestamp of when a user visited your site as a cookie. You can check out your browser cookies and a cookie will have the name wpb_visit_time.
How to Obtain Cookies and Use Them in WordPress
Now that a cookie has been created and stored in the user browser for one year, you can then use it on your WordPress website. It is easier if you know the name of a cookie as you can call it in PHP using the $_COOKIE variable. The code will then use the info stored in the cookie and will output it using shortcode. Shortcode can then be added to your site as [greet_me], showing you when a user last visited. This can also be altered to show recent posts to frequent users or popular posts to new people on your site.
Deleting a Cookie in WordPress
Deleting a cookie in WordPress requires you to add a line of code. This is unset($_COOKIE [‘wpb_visit_time’]); When you are doing this, it is important that you remember to replace wpb_visit_time with the title of the cookie that is being deleted.
This code will delete the cookie after the info that was stored inside has been used. You can then set the cookie again with the updated time info.
There you have it! You can now set, get and delete cookies on your WordPress website!