In order to understand transients, it’s helpful to have some basic knowledge of caching and Application Programming Interfaces (APIs).
Caching webpage data is essentially a way of temporarily saving a website’s data so that if there are multiple requests for the same data, the site doesn’t have to re-run MySQL or PHP. This can save seconds of time and reduce server load.
The idea is to keep data around temporarily, hence the word “transients.” The Transients API is similar to the WordPress Options API. You give data a name and a value—which can be complex, like a multi-level PHP array—and it stores the data. Later, perhaps even on a different request, you can retrieve that data using its name. The difference is that data in the Options table will stick around forever. That is, you can store data, and three years later, it will still be there.
Every transient is made up of three parts:
- $transient. This is the string used to identify your transient and call it up. It’s also referred to as the transient’s ‘key’ or ‘name’.
- $value. This is the information being retrieved via an API. A transient’s value can be an object, an array, a number, or a string.
- $expiration. This is how long a transient stays in your database, before it’s deleted and you have to access the information you need through the API again.
On the surface, that’s all there is to WordPress transients. However, in order to use them properly, there’s more you need to know.
Transients data will not stick around, however. That’s the point! You can request the data, and find that it’s missing in one of two ways. First, when you store the data, you specify an expiration date. For example, you could say “store this for three hours.” So if you request it after four hours, it will be missing.
The second way is that piece of data is allowed to simply vanish, at any time, for any reason. That sounds odd I know! What’s the point of storing the data if you can’t count on it? The point is that the storage is a request which WordPress will attempt to honor, but because of this flexibility, it’s possible to use different kinds of implementations for transient storage, and that means it’s possible to use different, advanced technology to make transients extremely efficient, and operate properly even in a multi-server clustered environment.
Because of this “vanish at any time” thing, you generally use transients for a cache. That is, if you need to compute something that takes real time, like a slow MySQL query, or retrieving data from an external source like someone’s Twitter or RSS feed, you can store the computed data in a transient, knowing that if it goes missing it’s always possible to recreate it. But in the usual case — when it does NOT go missing — you have the data quickly without having to recompute.