WordPress isn’t known for being the fastest website solution on the market – but there are a lot of little tricks that you can do as a developer to make everything run faster. Last week I did an article on creating a WordPress .htaccess file for increased performance. This week I want to look the Transient API which allows for caching data. This API is espcially useful for things like API calls which I covered in my articile on how to perform API calls with cURL (in fact you should read that article before going into this one).
What is the Transient API
The Transients API 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. The Transients API works in a very similar way to the Options API but with the addition of a lifespan for the transient. This allows it to be deleted when it expires which prevents database clutter. When an attempt to retrieve an expired transient takes place its removed from the database.
Last Time On DobsonDev…
When I did my tutorial on API calls with cURL (again – you should read that article before attempting this one if you’re unfamiliar with cURL calls) we ended up with the following code:
This code will call the GitHub API and retrieve the
README.md file from the repository and display it using the Parsedown PHP markdown parser. This code needs to be put into either your
functions.php file with the
Parsedown.php in your theme directory, or you can put it all into a plugin which would be a lot better practice.
In this tutorial we will expand on the above code to include a transient that will cache the results so we don’t have to call the API every single time the page is loaded. On top of less API calls we also won’t have to parse the markdown every time either since we will save the parsed content to our transient.
Checking the Transient
Using a transient involves two very easy to handle situations:
- We will check to see if the transient exists, if it does then we will return it
- If the transient doesn’t exist then we will do the API call and then create the transient from the data
To get started we will check if our transient exists. To do this all you have to do is call
get_transient( … ) with the transient name passed in and check if it returns
false. Since we also want to get the data if it’s not
false we will put our assignment within our if statement as well so that we can use that data later if the transient does in fact exist. It’s a little easier to understand if you see the code so check it out below:
As you can see, within our
if ( … ) statement we assign the transient to a variable and check to see if it returns
false. If it returns
false it means that the transient either didn’t exist or it was due to expire so it was deleted.
Creating the Transient
Creating the transient is a very simple matter (using transients is actually quite a simple matter), all we have to do is pass the data from our API call (which can be seen above) to the
set_transient( … ) function. We just have to shuffle things around a little at the end like this:
You can see that the only change we really did was save the parsed markdown to a variable which we then used to set our transient, once that’s done we return it so it displays. Now the next time we call the shortcode it should find the transient and will use it instead of calling the API.
The complete shortcode will look like this:
There is some extra
var_dump( … ) calls in there just to show you when the shortcode is setting the transient opposed to getting it from the database. If you put this code into production be sure to remove these and to change the function prefix (
unique_slug) to your theme’s or plugin’s prefix.
The other thing you might not be aware of is the time constant I used when creating the transient. WordPress has these built in to make things like this easier since you have to pass in the time in seconds. In my example I make the transient last for 12 hours but feel free to use whatever time you want. Built into WordPress are:
MINUTE_IN_SECONDS = 60 (seconds) HOUR_IN_SECONDS = 60 * MINUTE_IN_SECONDS DAY_IN_SECONDS = 24 * HOUR_IN_SECONDS WEEK_IN_SECONDS = 7 * DAY_IN_SECONDS YEAR_IN_SECONDS = 365 * DAY_IN_SECONDS
A Few Things to Note
There are a couple of things to note about this code and transients in general. Firstly this code wouldn’t work if you had more than one
README.md files displaying on your site. Every time it would grab the one that was saved as a transient. The way around this would be to include the
$repo or even better both in the name of the transient. The major problem with this is that transient names should be 40 characters or less in length, which is pretty easy to fill up.
One way around this (the one I’ve used in my DobsonDev Shortcodes plugin which is where this code is from) is to create a shortcode property called
cache_id which I append to the transient name. The user can then give each shortcode an ID which will ensure that each transient has a different name so they only get the correct one. I also use that property to see if the user even wants to cache results – if it’s not set then it will just do an API call every time. It could be possible that a user updates their
README.md file very frequently and doesn’t want to have to update the
cache_id every time they do that so they would rather just call the API every page load for convenience (updating the ID would be pretty much the same as refreshing the cache – the only problem is the previous transient might linger in the database but there are plugins that will clear expired transients for such a situation), so I give them the power to do that. You can see the function directly from my plugin below:
EDIT: I’ve written another article centered entirely on getting around the name length using by using MD5 when naming WordPress transients.
Another very important thing to note about transients is that they should NEVER be used for any information you aren’t willing to lose. It’s extremely important to remember that transients can and will be deleted automatically, so never store anything you can’t get back easily. The fact you can just make another call to get your information back is what makes API calls especially suited to being stored in transients. API calls aren’t the only thing transients are good for mind you, extremely complex queries (which WordPress is full of) are also a really great thing to use transients for to increase page load times.
That’s all I have for today, but it should be a really good start for learning about transients. If you want to do more reading check out the Transient API page on the Codex or check out this great article on CSS Tricks by Scott Fennel that covers a lot about transients (I didn’t even know about transients before reading his article). In that article he also uses WordPress’ HTTP API which I would love to learn more about and do an article on, but that’s for another day.
As always thank you for reading and please share it around as much as you can! Please feel free to put any suggestions or ideas for future tutorials in the comments section below.