← Tous les articles

Caching external API calls in WordPress with transients

A reviews, weather or stock widget that calls an API on every page view slows the whole site down and breaks it when the API fails. Transients fix both, as long as you avoid a few traps.

Caching external API calls in WordPress with transients

Key points

  • An HTTP call inside a template adds its response time to every single page view.
  • get_transient() returns false when nothing is cached, so an empty array is a valid cached value.
  • Keep a backup copy so the site still renders when the API stops responding.

A client got in touch because their homepage sometimes took several seconds to load, but only on certain days. The culprit was a “Customer reviews” block that queried a review platform on every request. When the API was slow, so was the whole site; when it returned an error, the block printed a PHP warning. The fix was about twenty lines of code using the WordPress Transients API.

Call the API once, serve the copy afterwards

A transient is a value stored with an expiry time. Without a persistent object cache it lives in the wp_options table; with Redis or Memcached it goes straight to that cache instead. Your code doesn’t change either way:

function wts_get_reviews() {
    $cached = get_transient( 'wts_reviews' );
    if ( false !== $cached ) {
        return $cached;
    }

    $response = wp_remote_get( 'https://api.example.com/v1/reviews', array( 'timeout' => 5 ) );

    if ( is_wp_error( $response ) || 200 !== wp_remote_retrieve_response_code( $response ) ) {
        // API down: serve the last good copy and retry in 5 minutes
        $fallback = get_option( 'wts_reviews_backup', array() );
        set_transient( 'wts_reviews', $fallback, 5 * MINUTE_IN_SECONDS );
        return $fallback;
    }

    $reviews = json_decode( wp_remote_retrieve_body( $response ), true );
    if ( ! is_array( $reviews ) ) {
        $reviews = array();
    }

    set_transient( 'wts_reviews', $reviews, HOUR_IN_SECONDS );
    update_option( 'wts_reviews_backup', $reviews, false ); // false = not autoloaded
    return $reviews;
}

A few details matter. The strict false !== $cached check means a legitimately empty list still gets cached, instead of triggering an API call on every request. The explicit 5-second timeout keeps PHP from hanging (it matches the default, but we write it down so it’s a deliberate choice). And the backup copy, stored in a non-autoloaded option, means an API outage doesn’t leave the block empty.

Traps we keep running into on live sites

  • Transients can vanish before they expire. With an object cache, Redis may evict them under memory pressure. Never put anything in a transient that you can’t rebuild.
  • Caching failures for too long. Cache an error for an hour and the site keeps showing stale data for an hour after the API recovers. That’s why the error branch uses a short lifetime.
  • Per-user keys without an object cache. One transient per visitor fills wp_options with thousands of rows. For personal data, use the object cache or a dedicated table.
  • Overlong names. Transient names are capped at 172 characters. If you build keys from parameters, hash them with md5().

Refresh in the background, not during a visit

With the code above, the first visitor after expiry waits for the API. On a busy site, several concurrent requests can even hit the API at once. The simple fix is to refresh the cache from a scheduled event:

add_action( 'wts_refresh_reviews', function () {
    delete_transient( 'wts_reviews' );
    wts_get_reviews();
} );

add_action( 'init', function () {
    if ( ! wp_next_scheduled( 'wts_refresh_reviews' ) ) {
        wp_schedule_event( time(), 'hourly', 'wts_refresh_reviews' );
    }
} );

WP-Cron only runs when someone visits. On our projects we disable it and trigger it from a real server cron job instead, so the refresh happens on schedule, overnight included.

Checking that the cache actually works

The quickest check is the Query Monitor plugin: its “HTTP API Calls” panel should be empty on a page served from cache. From the command line, wp transient get wts_reviews shows the stored value and wp transient delete wts_reviews forces a fresh call.

FAQ

Do I need Redis to use transients?

No. Without an object cache, WordPress stores them in the database, which is fine for a handful of values shared by all visitors. Redis pays off when you have many transients or they’re read constantly.

Do expired transients pile up in the database?

WordPress deletes them when something tries to read them, and a daily task cleans up the ones nobody reads any more. Transients saved without an expiry, however, stay until you delete them.

Is your WordPress site at the mercy of third-party APIs? We audit and tune the performance of production WordPress sites.

Partager LinkedIn Facebook X WhatsApp
</>

webtestudio

Agence web : sites WordPress sur mesure, thèmes premium et logiciels SaaS.

Parler de votre projet →