Given the state of many modern web applications, one of the things that I think surprises many developers when coming to WordPress is that the application is stateless.
That is, it doesn’t maintain any type of session using the conventional PHP
$_SESSION utilities. If you’re building a web application on top of WordPress where users will be required to login, you may want to introduce something like this.
At the very least, you may be interested in using cookies to manage certain settings for users who have signed in on the front-end using some type of custom functionality you’ve built.
To that end, here’s how to set cookies in WordPress.
Set Cookies in WordPress
Given that a user will be submitting their information via a form on the front-end and given that it will include their username and password, you’ll naturally want to verify them before creating and setting a cookie.
Once that’s done, setting a cookie in WordPress is as easy as doing the following:
As the code comment reads, this gist assumes that all of the user validation is already done. Next up, we’re just using PHP’s native setcookie function in order to create a cookie for the user related to the username that was just authenticated.
In the code above, I’m setting the cookie to expire in seven days, but the unit of time is arbitrary. You can even set it up such that it uses a value that the user has selected from the homepage (think of the “Remember Me For 30 Days” check boxes).
Of course, at some point, you’ll also want to delete the cookie such as if the user logs out of the application or some other action forces them out of the system. This is just a little bit trickier:
Unlike in the first example, we’re doing two things rather than one:
- We’re removing the value of the user’s cookie from the `$_COOKIE` collection
- We’re forcing the cookie to expire
The code that follows that logic is nothing more than an example to show what can be done (like redirecting users to the homepage). Technically, you can do anything you’d want here – especially any other house cleaning – but at some point, you’ll want to take the user away from any of the pages they can access when they’re logged into the system.