WordPress offers a great and simple solution for storing temporary data in the database.

It’s called Transients.

It’s ideal for storing data that is temporary, heavy to produce, but frequently used.

This way, we serve this cached data quickly and easily from the local DB, instead of processing the data on each page load.

This is an easy win: It improves the overall site performance which makes the user experience better, and also saves unnecessary API requests (which may have a limitation) in case this data is fetched from an external service.

Let’s look at this example:

// Use the cached API response, if exists.
$weather = get_transient( 'weather' );

// If there is no cached data, fetch it from the Weather API.
if ( empty( $weather ) ) {
    global $weather_api;
    $weather = $weather_api->get_data();

    // Save the API response for an hour, so there is no need
    // to perform a new API request within this time frame.
    set_transient(
        'weather',
        $weather,
        HOUR_IN_SECONDS
    );
}

// Use $weather.

Suppose we want to fetch weather data from an external service using its API.

Usually, there’s no reason to fetch this kind of data on each page load as it doesn’t change that often.

We can easily cache the data for one hour and retrieve it from the local DB.

So in the code above, we first check if the data exists locally with get_transient.

If it exists, we serve it from there.

If it doesn’t exist (empty( $weather )), it means that more than an hour has passed since the last API request and it’s time to fetch the fresh data again.

At this point, we perform the API request. We then use set_transient to locally cache the data we’ve just received for one hour (HOUR_IN_SECONDS) so that on the next page load, it will be served from the local DB.

We now have the weather data (whether from the local DB or from the new API request) available in $weather and ready to use.

References