Simple Cache with the WordPress Transient API

Today is our last post of our Advents Calendar, we hope you enjoyed it. WP Engineer wishes a Merry Christmas to our readers!

WordPress has an API that is explicitly designed for time-controlled storage of data – the Transient API. This API is designed to cache any data in the database and very simple to use it.

The first step is to get the entry from the database that will serve as content for the tag cloud – $tag_cloud = get_transient( 'tag_cloud' );. If this entry is missing, then the tag cloud is normally produced by the template wp_tag_cloud(). The only difference from the “normal” use in the template of the theme, the direct output is set on FALSE, because we need it in a variable.
In the following we will now set the entry in the database with the content and give a time value with it: set_transient($transient, $value, $expiration);. The time value, parameter three, is specified in seconds.
Now only the value of the variable has to be output and it’s done; from now gets the tag cloud the data from the cache, which exists for a period of 12 hours and then rebuilt.

$tag_cloud = get_transient( 'tag_cloud' );
if ( false === $tag_cloud || '' === $tag_cloud ){
	$args = array('echo' => false);
	$tag_cloud = wp_tag_cloud( $args );
	set_transient( 'tag_cloud', $tag_cloud, 60*60*12 );
echo $tag_cloud;

This small example illustrates the possibilities, the Transient API provides some additional functions, you can read about more in the Codex.





4 responses to “Simple Cache with the WordPress Transient API”

  1. Pippin Avatar

    Excellent! Is there any data that shows the kind of performance boost this gives for each page load, by retrieving data from the cache, rather than getting new data everytime?

  2. rzepak Avatar

    Advents Calendar was great! Thank you!
    and Merry Christmas WP Engineer

  3. Brian Krogsgard Avatar

    Very nice series guys. I enjoyed it throughout, and learned some new things!

    Merry Christmas!

  4. Dustin Montgomery Avatar

    Great information, I didn’t know this caching was built in!