Joomla & WordPress Tutorials, Info, Discussion, Tips | GavickPro Blog

WordPress Quick Tip #3 – Transient API

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.

WordPress offers a lot of different APIs which you should know about to help implement your solutions more quickly. The Transient API, specifically, is a great example of something you can implement in WordPress which , in most other CMS products, would require a lot of additional code. With WordPress and the Transient API you can implement a cache mechanism based on the database with just few lines of code!

The API exposes three functions:

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:

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.

Share