WordPress Transients API
The Transients API is a built-in WordPress feature that allows developers to store cached data temporarily in the database with an optional expiration time. It’s used to improve performance by reducing expensive or repetitive operations such as API calls or complex queries.
Why Use Transients?
- Reduces database load and improves speed
- Ideal for storing temporary data like:
- Remote API responses
- Processed shortcodes
- Query results
- Third-party data
How It Works
A transient is stored with a name, a value, and an optional expiration time (in seconds).
Set a transient:
set_transient( 'my_cached_data', $data, 3600 ); // 1 hour
Get a transient:
$data = get_transient( 'my_cached_data' );
Delete a transient:
delete_transient( 'my_cached_data' );
If the data has expired or doesn’t exist, get_transient()
returns false
.
Where Is It Stored?
- By default, transients are stored in the WordPress options table (
wp_options
) - If object caching (e.g., Redis or Memcached) is enabled, transients may be stored in-memory instead, improving performance
Real-World Use Case
Cache a remote API response to prevent repeated calls:
$response = get_transient( 'weather_data' );
if ( false === $response ) {
$response = wp_remote_get( 'https://api.weather.com/data' );
set_transient( 'weather_data', $response, 1800 );
}
Notes & Limitations
- Transients are not guaranteed to persist (especially without object caching)
- Ideal for non-critical, rebuildable data only
- Use a unique name prefix to avoid conflicts