How to cache data using WordPress transients
In the previous snippet we discussed how to use Php to fetch some data from a remote Api. These Api request take time to resolve, and should preferably be cached to speed up page load. In this snippet we will take a look at WordPress transients which can be used to cache our data.
“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.” ~ Common APIs Handbook
Maybe Cache function
In the code above we create a new function called maybeCache that accepts three parameters.
- $cache (String). Tha name of our cache/transient.
- $time (Int): Time until expiration in seconds.
- $callback (Function): A function that produces the data to cache.
Inside our new function we first check if our data is already cached by calling the get_transient function and passing it the name of our cache/transient. If there is a valid transient we simply return that data.
Next we use the call_user_func function to call the provided callback function and store its return value in a variable $data. We immediately pass the $data variable along with the $name and $time variables to the set_transient function which will .store our cache/transient in the database.
Finally we return the cached $data variable.
Using the maybeCache function
In the snippet below we combine our new maybeCache function with the do_remote_get function from the previous snippet/article.
Here we use the maybeCache function and pass it:
- remote_posts_data: As the name of our transient.
- 7200: The time in secconds that our cache is valid (7200s = 2 hours).
- A anonymous callback function.
Inside our anonymous callback function we call the do_remote_get function to fetch some posts data from a remote Api and return that data.
On first execution the maybeCache function will store the data from the Api inside the database. And on subsequent requests it will return that cached data until our 2 our expiration time has passed, after which the data is invalid and must be called from the Api, and stored again.
Finally, as in the previous snippet, we loop over the posts and echo out their titles.
Note: WordPress transient can also be used to cache results of expensive database queries or html fragments that take a lot of processing. But remember that the transients Api uses database queries them selfs to retrieve their data so be wise and don’t over use them.
If you want to leave a comment, please do so under the copy of this article on Dev.to so i can get back to you.
Thanks for reading