Many things a WordPress site does are expensive: calling an external API for weather, exchange rates or social feeds, running a complex database query, generating a large HTML fragment or calculating statistics. Doing that work on every page load wastes time and server resources, and sometimes hits rate limits on external services.
The Transients API is WordPress’s built-in way to store the result of expensive work temporarily, with an expiry time. The next request can reuse the stored result instead of doing the work again.
Transients are simple to use and easy to misuse. I’ve cleaned up options tables with hundreds of thousands of orphaned transient rows, and fixed sites that slowed to a crawl every hour when a popular transient expired and dozens of requests rebuilt it at once. Here’s how to use transients properly.
The basics
Three functions cover most needs:
- $key is a unique name for the cached value. Keep it under 172 characters and prefix it with your plugin or theme name.
- $value can be any serialisable data: strings, numbers, arrays or objects.
- $expiration is the maximum lifetime in seconds. WordPress provides constants like MINUTE_IN_SECONDS, HOUR_IN_SECONDS and DAY_IN_SECONDS.
The typical pattern:
| if ( is_wp_error( $response ) | 200 !== wp_remote_retrieve_response_code( $response ) ) { |
|---|
Check for false with strict comparison. A cached value could legitimately be zero, an empty string or an empty array, which a loose check would treat as missing.
Where transients are stored
This is the most important thing to understand about transients:
- Without a persistent object cache, transients are stored in the wp_options table, as two rows: one for the value and one for the expiry time.
- With a persistent object cache, like Redis or Memcached, transients are stored in the cache instead, and the database isn’t used.
That difference has consequences:
- In the database, expired transients aren’t necessarily deleted when they expire. They’re removed when someone tries to read them, or by WordPress’s periodic cleanup. Sites with many unique transient keys can accumulate large numbers of rows.
- In an object cache, transients can disappear at any time, even before their expiry, if the cache evicts them to free memory.
Transients are not guaranteed storage
The expiration is a maximum, not a promise. A transient can disappear before it expires: the object cache may evict it, a cache flush may clear it or a plugin may delete it.
Your code must always handle a missing transient by regenerating the data. Never use transients to store data you can’t recreate, like user input or settings. For permanent data, use options, post meta or custom tables.
Good uses for transients
- External API responses, like social feeds, weather, exchange rates or shipping rates for common requests.
- Expensive query results, like popular posts, complex aggregations or counts.
- Generated HTML fragments, like a complex navigation menu or a widget’s output.
- Rate limiting data, with care, such as tracking how many times an action happened in a short window.
Poor uses for transients
- Data you can’t regenerate.
- Per-user data at large scale without an object cache, like a transient per visitor. Without a persistent cache, that means database rows per visitor, quickly bloating the options table.
- Very large values, like huge arrays of data, which slow down storage and retrieval.
- Data that changes on every request, where caching provides no benefit.
Choosing expiration times
Pick an expiration that balances freshness and performance:
- Exchange rates: an hour or a few hours.
- Social media feeds: 15 minutes to an hour.
- Popular posts lists: an hour or a day.
- Heavy reports: a day.
Avoid transients with no expiration in the database. Non-expiring transients are stored as autoloaded options, meaning they load on every request, which defeats the purpose and can slow the whole site. If you need a value with no expiry, consider whether it should be an option instead.
Invalidating transients when data changes
Waiting for expiry isn’t always good enough. If you cache a list of featured products, and an editor changes which products are featured, the cached list should update immediately. Delete the transient when relevant content changes:
Think about every event that should refresh cached data: saving posts, updating terms, changing settings or receiving webhooks.
Avoiding cache stampedes
A cache stampede happens when a popular transient expires and many simultaneous requests all find it missing, all start regenerating it at once and all hit the database or external API together. On busy sites, this can cause noticeable slowdowns or rate limit errors every time the transient expires.
Ways to prevent stampedes:
Refresh in the background
Instead of regenerating data during page loads, refresh it on a schedule with WP-Cron or Action Scheduler, before it expires. Page loads always read the cached value.
Schedule the refresh hourly, while the transient lasts two hours, so it never expires under normal operation.
Serve stale data while refreshing
Store the data with a timestamp in a longer-lived transient. If the data is older than your freshness limit, serve the stale data and trigger a background refresh, rather than making visitors wait.
Use a short lock
When regeneration starts, set a short-lived lock so other requests don’t start regenerating at the same time. They serve the old value or a fallback until the new value is ready.
Handling failures
When external APIs fail, don’t cache the failure for a long time, and don’t keep hammering the API on every page load either. A practical approach:
- On success, cache for the normal duration.
- On failure, return the last good data if you have it, and cache a short “retry later” marker for a few minutes, so requests don’t all retry immediately.
Site transients for Multisite
On Multisite networks, set_site_transient and get_site_transient store values for the whole network rather than one site. Use them for data shared across all sites.
Naming and organisation
- Prefix keys with your plugin or theme name to avoid clashes.
- Include variables in keys when caching per item, like mysite_product_stats_123, but beware of creating huge numbers of unique keys without an object cache.
- Keep keys predictable, so you can delete them when data changes.
Cleaning up transients
Without an object cache, expired transients can accumulate in the options table. Clean them up periodically:
If you see huge numbers of transients even after cleaning, a plugin is creating too many unique transient keys. Identify it and fix or replace it.
When your plugin is uninstalled, delete its transients along with its options.
Transients versus the object cache API
WordPress also provides wp_cache_get and wp_cache_set, which use the object cache directly. The difference:
- Object cache functions only persist between requests if a persistent object cache is installed. Without one, the data lasts only for the current request.
- Transients persist in the database when there’s no persistent cache, and in the cache when there is.
Use object cache functions for data that’s fine to lose between requests on sites without a persistent cache, and transients when you want persistence either way.
A real-world example
A client’s homepage displayed a feed from an external review service. Every page load called the service’s API directly, which was slow and occasionally failed, making the homepage slow or broken. We moved the API call into a transient with an hour’s expiry, refreshed by a scheduled task, and stored the last good response as a fallback. Page loads became fast and stable, and the external service received a handful of requests per day instead of thousands.
That’s the essence of good transient use: do expensive work rarely, reuse results often and always have a fallback when the outside world misbehaves.
Treat every transient as disposable, and your code will stay robust.
Name keys clearly
Use descriptive transient names that explain what they hold. Future developers debugging a cache issue will thank you.
Frequently asked questions
Do transients slow down my database?
Used well, they speed sites up. Problems come from huge numbers of unique transients, non-expiring transients that are autoloaded and very large values on sites without a persistent object cache.
Why does my transient disappear before it expires?
With a persistent object cache, transients can be evicted when memory is full or flushed when the cache is cleared. Always handle missing transients.
Should I store user data in transients?
Only short-lived, regenerable data, and be careful with per-user transients on sites without a persistent object cache.
How do I clear all transients?
wp transient delete –all clears them. Expect a temporary slowdown while caches rebuild.
Final thoughts
Transients are a simple, powerful way to avoid repeating expensive work. Cache API responses, query results and generated output with sensible expiration times, always handle missing values, invalidate caches when underlying data changes, refresh popular data in the background to avoid stampedes and clean up after yourself. Understand where transients are stored on your site, and they’ll make it faster rather than heavier.




