Do you find yourself needing to store temporary or cache data for your widgets or themes? Use the Transient API – it is by far the best way to quickly and effectively implement your storage needs.
The API exposes three functions:
- set_transient
- get_transient
- delete_transient
I think their names are obvious descriptions of their functionality. :)
Let’s look more closely at each of these three functions. To begin, we will store some data:
set_transient('gk_transient_data', 'some text data', 4 * 60 * 60);
In this example, our code will create a field to store the string ‘some text data’ under the key ‘gk_transient_data’, and these data elements will be available for a maximum of 4 hours.
Now, let’s read our stored data:
get_transient('gk_transient_data');
If the gk_transient_data is read before the expiration period has elapsed, this function will return the string ‘some text data’. Otherwise, if we only read this transient data after four hours, this function will instead return a boolean false value (remember to check it with the “===” operator!).
OK, so what if we want to clear out our transient data before 4 hours have passed? We should then use the following code:
delete_transient('gk_transient_data');
If the transient data still exists, this function will now remove it and return a boolean true. If the data no longer exists (maybe it has already expired), the function will return a boolean false.
Additional Information
set_transient will also update data if the key name indicated as the first argument exists in the database (gk_transient_data, in our example).
Setting the expiration time in the set_transient function to 0 will create transient data which never expires. Be careful! Transient data which never expires are autoloaded by default, so it will impact your page loading speed, affecting site performance. Of course, this is not the appropriate usage of transient data, which is intended to be temporary.
There are also the multisite versions of the above functions:
- set_site_transient
- get_site_transient
- delete_site_transient
Usage examples
You can use the transient data as a cache for data which cannot be downloaded for every page request. We have used the transient data as a cache in our GK Weather widget in the News theme.
The transient data can be used as a cache for the widgets output. Some of our widgets, such as GK News Show Pro, use the Transient API to cache their output.