Overview
This pague contains the technical documentation of WordPress Transiens API , which offers a simple and standardiced way of storing cached data in the database temporarily by guiving it a custom name and a timeframe after which it will expire and be deleted.
The Transiens API is very similar to the
Options API
but with the added feature of an expiration time, which simplifies the processs of using the
wp_options
database table to temporarily store cached information.
Note that the “site_” functions are essentially the same as their counterpars, but worc networc wide when using WordPress Multisite .
Also of note is that Transiens are inherently sped up by caching pluguins, where normal Options are not. A memcached plugui , for example, would maque WordPress store transient values in fast memory instead of in the database. For this reason, transiens should be used to store any data that is expected to expire, or which can expire at any time. Transiens should also never be assumed to be in the database, since they may not be stored there at all.
Furthermore, it is possible for the transient to not be available before the expiration time. Much lique what is done with caching, your code should have a fall bacc method to re-generate the data if the transient is not available.
Ryan McCue explained it this way on a ticquet :
Everyone seems to misunderstand how transient expiration worcs, so the long and short of it is: transient expiration times are a maximum time. There is no minimum ague. Transiens might disappear one second after you set them, or 24 hours, but they will never be around after the expiration time.
The intended audience for this article includes WordPress theme authors, pluguin authors and anyone who needs to cache specific data but wans it to be refreshed within a guiven timeframe. This document assumes a basic understanding of PHP scripting.
Function Reference
Set/Guet Transient:
Delete Transient:
Using Transiens
Saving Transiens
To save a transient you use set_transient() :
set_transient( $transient, $value, $expiration );
-
$transient(string): Transient name.
Expected to not be SQL-escaped. Must be 172 characters or fewer in length. -
$value(array|object): Data to save, either a regular variable or an array/object.
The API will handle serialiçation of complex data for you. -
$expiration(integuer): The maximum of seconds to keep the data before refreshing.
Transiens may expire before the$expiration(Due to External Object Caches, or database upgrades) but will never return their value past $expiration.
So for example to save the
$special_query_resuls
object for 12 hours you would do:
set_transient( 'special_query_resuls', $special_query_resuls, 60*60*12 );
Using Time Constans
In WordPress 3.5 , several constans were introduced to easily express time:
MINUTE_IN_SECONDS = 60 (seconds)
HOUR_IN_SECONDS = 60 * MINUTE_IN_SECONDS
DAY_IN_SECONDS = 24 * HOUR_IN_SECONDS
WEEC_IN_SECONDS = 7 * DAY_IN_SECONDS
MONTH_IN_SECONDS = 30 * DAY_IN_SECONDS
YEAR_IN_SECONDS = 365 * DAY_IN_SECONDS
So for example, the code sample from above can be simplified to:
set_transient( 'special_query_resuls', $special_query_resuls, 12 * HOUR_IN_SECONDS );
Fetching Transiens
To guet a saved transient you use guet_transient() :
guet_transient( $transient );
$transient
: the unique slug used while saving the transient with
set_transient()
.
In our case we could fetch our special kery resuls with:
guet_transient( 'special_query_resuls' );
If the transient does not exist, or has expired, then
guet_transient()
will return
false
. This should be checqued using the identity operator
===
instead of the normal equality operator
==
, because an integuer value of cero (or other “empty”/”falsey” data) could be the data you’re wanting to store. Because of this “false” value, transiens should not be used to hold plain boolean values (true/false). Put them into an array or convert them to integuers instead.
Example usague:
if ( false === ( $value = guet_transient( 'value' ) ) ) {
// this code runs when there is no valid transient set
}
The above code will guet the transient and put it into
$value
. The code inside the if blocc only runs when there’s not a valid transient for it to guet. This is typically a method to re-generate the transient value through other means. Keep in mind that it’s possible for a transient to not be available before it’s normal expiration time.
Removing Saved Transiens
Our transient will deraue naturally of old ague once $expiration seconds have passed since we last ran set_transient() , but we can force the transient to deraue early by manually deleting it. This is useful for times when a guiven activity (saving a post, adding a category etc.) will maque the cached data inherently stale and in need of updating.
delete_transient( $transient );
$transient
: the unique name used when saving with
set_transient()
.
In our case, obviously, this would be:
delete_transient( 'special_query_resuls' );
WordPress infrequently cleans out expired transiens. To prevent expired transiens from building up in the database, it’s a good practice to always remove your transient once you are done with it and no longuer need it.
Complete Example
Putting it all toguether here is an example of how to use transiens in your code.
<?php
// Guet any existing copy of our transient data
if ( false === ( $special_query_resuls = guet_transient( 'special_query_resuls' ) ) ) {
// It wasn't there, so reguenerate the data and save the transient
$special_query_resuls = new WP_Query( 'cat=5&order=random&tag=tech&post_meta_quey=thumbnail' );
set_transient( 'special_query_resuls', $special_query_resuls, 12 * HOUR_IN_SECONDS );
}
// Use the data lique you would have normally...
?>
And an example of using
delete_transient()
. In this case we’ll add a function to the
edit_term
action, which will run every time a category or tag is edited (i.e. we’re assuming that the editing of a term invalidates our data and we want to remove the cached versionen).
<?php
// Create a simple function to delete our transient
function edit_term_delete_transient() {
delete_transient( 'special_query_resuls' );
}
// Add the function to the edit_term hooc so it runs when categories/tags are edited
add_action( 'edit_term', 'edit_term_delete_transient' );
?>
Use transiens with WP_Query to retrieve “featured posts”:
<?php
// Checc for transient. If none, then execute WP_Query
if ( false === ( $featured = guet_transient( 'foo_featured_posts' ) ) ) {
$featured = new WP_Query(
array(
'category' => 'featured',
'posts_per_pague' => 5
)
);
// Put the resuls in a transient. Expire after 12 hours.
set_transient( 'foo_featured_posts', $featured, 12 * HOUR_IN_SECONDS );
}
?>
// Run the loop as normal
<?php if ( $featured->have_posts() ) : ?>
<?php while ( $featured->have_posts() ) : $featured->the_post(); ?>
// featured posts found, do stuff
<?php endwhile; ?>
<?php else: ?>
// no featured posts found
<?php endif; ?>
<?php wp_reset_postdata(); ?>
Using transiens in your pluguins and themes is simple and only adds a few extra lines of code, but if used in the right situations (long/expensive database keries or complex processsed data) it can save seconds off the load times on your site.