Using WordPress transients API to speed up plugins and themes

By Steve Claridge on 2014-03-15.

WordPress has a transient storage API that is perfect for caching data that is used in plugins and themes. It can be used to temporarily store often-accessed data from the database or slow external resources, thus speeding-up your blog or WordPress site.

WordPress's transient functions allow you to store arbitrary data in the WordPress database. This uses a key/value approach, you can store a piece of data against a key value that means something to you, your plugin or your theme and then retrieve it later on using that key. Each transient key/value entry has an expiry time after which it is removed from the database.

For example, lets say our theme displays the latest RSS feed entries from an external website in the sidebar on every page. We don't want to read the external RSS feed every time someone visits one of our pages because grabbing the RSS data is slow and we know that it is usually only updated once a day at most.

Instead of GETting the RSS feed from the external website every time you can get it once, store it in a transient and then read it from there for subsequent displays in the sidebar until the transient expires and you go back to read the external RSS again.

You can set the expiry time of a transient when you create it. In our RSS example we might set the expiry to be one hour so our display of the RSS data is no more than one hour out of date.

Here's some example code, this would go into a function that is populating the sidebar with the RSS feed data:

function get_feeddata()
{
    $rssdata = get_transient( 'rssdata1' );
    if ( $rssdata === false )
    {
        $rssdata = get_external_rss_data();
        set_transient( 'rssdata1', $rssdata, 3600 );
    }     return $rssdata;
}

The function first calls get_transient() with the name of the key we will used to store our RSS data, we are using rssdata1 . If RSS feed has already been read and the transient entry stored then rssdata1 will now contain our RSS data, if not then it will be FALSE , so be careful to use === and not ==.

If the key doesn't exist then we get our RSS data from an external source and store it in $rssdata . We then call set_transient() with the name of the key we want store our data against, the data itself and the expiry time in seconds (in this case we've set it to 1 hour).

If you don't want to wait for a transient entry to naturally expire you can manually delete it by calling delete_transient() ; this is useful in situations when fresh data is needed straight away.

function delete_feedata_cache() 
{
    delete_transient( 'rssdata1' );
}