When building complex WordPress themes or plugins, your code often performs heavy database queries, complex user calculations, or external API requests. Running these operations on every single page load can severely slow down your website and strain server resources.
While object caching or full-page caching plugins help, WordPress provides a built-in, lightweight caching system known as the Transients API. It allows you to store temporary data in the database (or an object cache if configured) with a predefined expiration time.
In this tutorial, we will walk through how to use the Transients API to cache heavy operations and boost your site’s performance.
1. Understanding How Transients Work
The Transients API is very similar to the Options API, but with one major advantage: every transient has an expiration time (timeout).
The three core functions you need are:
set_transient($transient, $value, $expiration) — Stores data for a specific period.
get_transient($transient) — Retrieves the cached data.
delete_transient($transient) — Clears/deletes the cached data manually.
2. Implementing Transients for Heavy Queries or API Calls
Instead of running an expensive operation on every page view, we check if a transient exists. If it does, we use the cached version. If it doesn’t, we fetch the fresh data, save it into a transient, and then use it.
Add the following pattern to your theme or custom plugin:
if (!defined('ABSPATH')) {
exit;
}
function wg_get_cached_expensive_data() {
$transient_key = 'wg_expensive_data_cache';
// 1. Try to get data from the transient cache
$cached_data = get_transient($transient_key);
// 2. If transient exists, return cached data
if (false !== $cached_data) {
return $cached_data;
}
// 3. Otherwise, perform the heavy operation (e.g., complex DB query or external API call)
global $wpdb;
$table_name = $wpdb->prefix . 'wg_submissions';
// Simulating a heavy query
$fresh_data = $wpdb->get_results("SELECT * FROM $table_name ORDER BY time DESC LIMIT 50");
// 4. Save data to transient for 12 hours (12 * HOUR_IN_SECONDS)
set_transient($transient_key, $fresh_data, 12 * HOUR_IN_SECONDS);
return $fresh_data;
}
3. Invalidating Transients When Data Changes
If your underlying data changes (for example, a new submission is added or a post is updated), your cached transient will display outdated information until it expires naturally. To prevent this, you should delete or update the transient whenever data is modified.
add_action('wp_insert_site_meta', 'wg_clear_submissions_transient'); // Or your custom data hook
function wg_clear_submissions_transient() {
delete_transient('wg_expensive_data_cache');
}
Best Practices for Transients
Always Check for false: Because a transient can store empty arrays or 0, always use strict comparison (false !== get_transient(…)) to check if the cache exists.
Use Appropriate Expiration Times: Set realistic expiration times using WordPress time constants like HOUR_IN_SECONDS, DAY_IN_SECONDS, or WEEK_IN_SECONDS.
- Avoid Dynamic Keys with Unlimited Variations: Never use user-specific data (like user IDs or raw search queries) to generate unique transient keys without limitation, as this can bloat your database options table.
Leveraging the WordPress Transients API is an easy and effective way to eliminate redundant database queries and speed up your custom themes and plugins without relying on complex external caching mechanisms.
Be sure to check out our previous tutorials on WordPress development:
Building Custom REST API Endpoints in WordPress
Creating Custom Database Tables in WordPress with dbDelta
Creating Custom Dashboard Widgets in WordPress
Need help with your project? We will be happy to help with your project. Feel free to contact us. Just reach out and we will reply soon.