Transients API in WordPress

The Transients API is very similar to the Options API but with the added feature of an expiration time, which simplifies the process of using the wp_options database table to temporarily store cached information. WordPress Transients API, which offers a simple and standardized way of storing cached data in the database temporarily by giving it a custom name and a timeframe after which it will expire and be deleted.

Saving Transients

To save a transient you use set_transient() :

$transient
(string) Transient name. Expected to not be SQL-escaped. Must be 172 characters or fewer in length.
$value
(array|object) Data to save, either a regular variable or an array/object. The API will handle serialization of complex data for you.
$expiration
(integer) The maximum of seconds to keep the data before refreshing. Transients may expire before the $expiration (Due to External Object Caches, or database upgrades) but will never return their value past $expiration.

So for example to save the $special_query_results object for 12 hours you would do:

Using Time Constants

So for example, the code sample from above can be simplified to:

Fetching Transients

To get a saved transient you use get_transient() :

  • $transient the unique slug used while saving the transient with set_transient().

In our case we could fetch our special query results with:

If the transient does not exist, or has expired, then get_transient() will return false. This should be checked using the identity operator (===) instead of the normal equality operator (==), because an integer value of zero (or other “empty”/”falsey” data) could be the data you’re wanting to store. Because of this “false” value, transients should not be used to hold plain boolean values (true/false). Put them into an array or convert them to integers instead.

Example usage:

The above code will get the transient and put it into $value. The code inside the if block only runs when there’s not a valid transient for it to get. This is typically a method to re-generate the transient value through other means. Keep in mind that it’s possible for a transient to not be available before it’s normal expiration time.

Removing Saved Transients

Our transient will die naturally of old age once $expiration seconds have passed since we last ran set_transient(), but we can force the transient to die early by manually deleting it. This is useful for times when a given activity (saving a post, adding a category etc.) will make the cached data inherently stale and in need of updating.

  • $transient the unique name used when saving with set_transient().

In our case, obviously, this would be:

WordPress infrequently cleans out expired transients. To prevent expired transients from building up in the database, it’s a good practice to always remove your transient once you are done with it and no longer need it.