Find out in this tutorial how to use WordPress transients to cache data transiently.
When you use code that performs database queries, this has an impact on web performance. Depending on the complexity of the query and the size of the database the impact will be higher or lower.
In any case it is always advisable to reduce the number of complex calculations to minimize the web load.
That’s why the WordPress Transient API is a very interesting tool, as it allows you to temporarily save data in the cache.
Specifically it temporarily stores cache data in the database in the wp_options table. And as the name suggests, this data is transient, so it has an expiration date.
Let’s see how it works and how to take advantage of it.
Steps to use transients in WordPress
1. Create a transient
To create a transient you have to use the following syntax:
set_transient( $transient, $value, $expiration );
Where:
- $transient > Unique name
- $value > Data you want to store
- $expiration > Maximum validity date (unix format)
The following expiration constants are normally used:
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
2. Retrieve a transient
Once you have created a transient you can retrieve it using the get_transient
function as follows:
get_transient( $transient );
Simple, isn’t it?
3. Remove a transient
In the same way you can delete a transient using the delete_transient
function as follows:
delete_transient( $transient );
4. Example of how to use a transient
So that you can see more clearly how it works, let’s use an example applying what you have just seen to the tutorial in which I explained how to show the subscribers’ favorite posts.
The code would look like this:
To see this and another 1097 code snippets of this website, login or subscribe here.
What you do in this case is add a couple of lines:
$count_array = get_transient( 'cached_favorited_posts' );
set_transient( 'cached_favorited_posts', $count_array, WEEK_IN_SECONDS );
With them you get to cache the array containing all the subscribers’ favorite posts (sorted from highest to lowest) during a week.
This way you reduce the calculation to once every 7 days, which in this case should be more than enough. But the idea is that you adjust it to your particular case. 😉
Conclusions
Now you know how you can use WordPress transients to cache data temporarily.
If you have any question, please leave it in the comments. And if you want to give me a suggestion for future snippets, please send it through the contact form.
Benefits of being a subscriber. 🙂