Caching in WordPress
In some cases, we might want to limit the amount of request we send to a server or send through our server, there can be various reasons for this like rate-limit, bandwidth saving etc. For that we can use caching, we can keep the fetched data saved somewhere until the data is changed or updated on the API.
To achieve this functionality, WordPress provides us with Transients,
Transients save the values in the database, they are not only limited to be used by HTTP API, they can be used anywhere for any kind of caching or storing information. The come with an expiration value as well which can be used if you want to expire them within a specified time frame.
How to use transients with HTTP API?
For example we want to get data from https://www.example.com and we don’t want to fetch the data everytime we fetch the page, instead we want to fetch the data only after 1 hour, this can be achieved by transients.
$response = wp_remote_get( 'https://example.com' );
set_transient( 'our_example_response', $response, 60 * 60 );
Now this would save the response into the transient named our_example_response
Let’s modify the code a bit to support the function we are trying ( fetching data only after 1 hours )
$response = get_transient( 'our_example_response' );
if ( false === $response ) {
$response = wp_remote_get( 'https://example.com' );
set_transient( 'our_example_response', $response, 60 * 60 * 60 );
}It is a good practice to use time constants instead of normal 60*60 for better readability.
Some of the time constants in PHP 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
- MONTH_IN_SECONDS = 30 * DAY_IN_SECONDS
- YEAR_IN_SECONDS = 365 * DAY_IN_SECONDS
Transients functions
- set_transient() -> This would set or update the transient value ( single function for updating and initiating ),
The first parameter is the name/identification for the transient.
The second parameter holds the data for the transient this can be anything ( can also be objects ) -> Serialization is taken care automatically
The third parameter is optional -> Expiry time in seconds -> By default: 0 -> No expiration ( The transient can still be expired ) - get_transient() -> This is used to retrieve/fetch the value of transient -> This would return false if the transient does not exists or is expired
This first parameter is the name of the transient - delete_transient() -> This is used to delete the transient value
The first parameter is the name of the transient to delete.
Transient is not always stored in the database -> We can change how the transient would work -> We can use custom cache objects as well to deal with transient -> The working we specify would affect how the transient expiry would be working
-> So we should not 100% rely on the expiry time of a transient
It can be expired even before it’s expiry time in some situations.
