What are transients in WordPress?

Transients are a simple way to cache data for a limited time, like the result of a slow query or a remote API call. You save a value with a name and an expiry time. After that time the value is gone and you make it again.

$key = 'tc_slow_data';

$data = get_transient( $key );
if ( false === $data ) {
	echo "Cache miss: building the data\n";
	$data = array( 'built_at' => 'now', 'items' => range( 1, 3 ) );
	set_transient( $key, $data, HOUR_IN_SECONDS );
} else {
	echo "Cache hit\n";
}

$again = get_transient( $key );
echo 'Second read: ' . ( $again ? 'cache hit, items: ' . implode( ',', $again['items'] ) : 'miss' ) . "\n";

delete_transient( $key );
var_dump( get_transient( $key ) );
Output

Cache miss: building the data
Second read: cache hit, items: 1,2,3
bool(false)

  • By default transients are saved in the wp_options table (with a _transient_ prefix). When a persistent object cache (Redis or Memcached) is installed, they go there instead.
  • Always check false === $data, because a transient can be missing at any time.
  • The expiry is a maximum. The cache can be cleared earlier.
  • Do not save sensitive data in transients.

For per request caching use wp_cache_get() and wp_cache_set() (the object cache).


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.