I’ve written about using cookies in WordPress before, but one of the thing about doing so is that they typically after to fire within the context of an init hook.
When working in an object-oriented fashion and trying to de-couple certain pieces of logic such that you can use them without having to rely on other hooks, it’s important to find ways to handle this.
Otherwise, the code becomes tightly-coupled, and you can have hooks, do_action calls, or anonymous functions all over the place.
To simulate the nature of cookies and their feature of expiration, using WordPress transients via the appropriately named Transients API may be a viable solution.
Using WordPress Transients
If you’re familiar with any of the metadata APIs that are in WordPress, then you’re likely familiar with the functions they use. This includes standard operations like add, get, update, and delete.
And with WordPress, you can simplify it in many places to update, get, and delete because update will first to see if a piece of information exists and, if not, will add it.
Designing a Class Interface
Thus, the interface for a class that wraps the Transients API could be reduced to:
- set,
- get,
- delete.
Where set replaces add and update. Furthermore, it’s nice to have helper functions like has that allow us to write conditionals in code that calls into the library.
For example, if you may want to do something like “if this has no value, then return.”
Thus, the interface for the code may look something like this:
There are some caveats to consider when working with code like this, too. That is, what about the case of authenticated users and non-authenticated users?
When that happens, there’s another way in which transient data may need to be handled (depending on your method of implementation above).
I can cover that in a follow-up post, though.
A Word of Caution
Here’s a thing to remember, though: It’s not a good idea to pollute the WordPress options table. And this is precisely where transients are stored.
So if you’re going to use WordPress transients, then make sure you’re not throwing a ton of values into the database.
Just what’s needed. And if a lot of data is needed, then perhaps you need to look at the architecture of your code or consider another type of database.