Using PHP Cookies in WordPress

Create your php cookies in WordPress

I’ve always been scared of creating PHP cookies. Cookies are an extremely widely used web technology consisting of little pieces of data that live on your device and remember things: for example, the last product you browsed on Amazon, or whether you’re already logged-in to Gmail. As common as they are, though, cookies have always felt like a spooky piece of web architecture that I presumed would be painful and complex to implement.

Then a client project came up that needed cookies, and guess what? They’re easy to write—much easier than, for example, baking cookies, which I still refuse to learn.

In this article, we’ll walk you through why, and how, to use cookies in WordPress.

Why Use PHP Cookies?

There are times when user account creation is too clunky a means to store persistent user data. Cookies can persist user data without requiring a login.

Websites have lots of user-specific data. A site might want to know all kinds of things to improve my user experience: my native language, the last time I visited, form information I’ve previously submitted, and so on. In many cases, this data needs to persist: it needs to last across site visits.

The most common way WordPress uses to persist data about site visitors is through WordPress user accounts. This system is really full-featured, with all kinds of user roles, permissions, data, metadata, and so on.

There are times, though, when it’s a bit too clunky. By default, it requires users to create an account—complete with, at minimum, a username, email, and password—and then log into that account. To just store a bit of very data (like, say, a user language preference or time zone), that’s an awful lot. Cookies can persist user data without requiring a login.

WordPress’s inbuilt cookie system works through its user system, and that’s not what we want. So here we’re kicking it old-school, with pure PHP that we wrap into a plugin.

A Demo PHP Cookie