A Quick Guide to the WordPress Transients API

The Transient API in WordPress is one of the many APIs available in the WordPress core that, once used, become invaluable and used on a daily basis. This is a quick guide to getting started with the transients API, when to use it and why.

The Transients API, while similar to the WordPress options API, has the addition of an expiry time. The API is used to store data in the database for a fix amount of time, at which point it is deleted and would need to be re-added, if one requires the data again. The WordPress Codex explains the Transients API as:

…very similar to the Options API but with the added feature of an expiration time, which simplifies the process of using the wp_options database table to store cached information.

From a technical standpoint, transients are also sped up by caching plugins, which store the data in memory, rather than in the database, making for a faster lookup.

Getting started

Using transients is easier than you might think. The first thing to note is that there are two types of transients; conventional (only on the specified site within a WordPress multisite installation) and “site” (across the entire WordPress multisite installation). They interact in the same way though.

The Transients API has 3 core functions; set_transient(), get_transient() and delete_transient(). They function in the same way as add_option(), get_option() and delete_option() do, so they should be familiar.

Brief function analysis

set_transient()

Stores data in a transient.

The parameters are:

  1. The transient key (the name of the transient to store the data in)
  2. The value (the data to store)
  3. The expiration (the time expiration, in seconds, from the time of storage – one day would be 60 * 60 * 24)

get_transient()

Retrieve the transient data, if it’s available.

The parameters are:

  1. The transient key (the name of the transient the data is stored in)

delete_transient()

Force the expiry/removal of a specified transient.

The parameters are:

  1. The transient key (the name of the transient the data is stored in)

The Transients API in use

To use the Transients API, the process is straight forward. Check if the transient is available. If it isn’t, get the data (this could be anything from a simple line of text -which may not be too practical- to an advanced and resource-intensive database query, which you may not want to run every time your website is loaded) and assign it to the transient. Assign the data to a variable and return it for use in your code.

In code, this may look like the following:

<?php
	$transient_key = 'my-transient-key';
	$data = get_transient( $transient_key );
	if ( $data == '' ) {
		$data = get_posts( array( 'posts_per_page' => -1 ) );
		set_transient( $transient_key, $data, 60 * 60 * 24 );
	}
	
	// You would then carry on using $data in your code.
?>

An example of when WordPress itself uses the Transients API is during checks for updates of themes, plugins and WordPress itself. These checks don’t in fact happen each time you visit the “Updates” dashboard screen, but periodically based on a transient of stored information about the themes and plugins you have in your installation.

Where and when to use the Transients API

Usage of this API is vast and varied. Essentially, the Transients API can be seen as a form of caching system with an expiry time. Therefore, you may want to cache data (for example, from an RSS feed or API request) for a few hours or days, or you could cache something for a few seconds while a user is busy on your website (to make their experience that little bit faster). With such simple implementation, the usage possibilities are limited only by one’s imagination and a coding project’s requirements.

Now that you know about the Transients API, I’m certain you’ll start using it more often to speed up your projects. This API, while seemingly so small and simple, is incredibly powerful and can transform bloated code into streamlined genius.

WordPress tips in your inbox ✨

More WordPress thoughts and tips, right in your inbox.

We don’t spam! Read our privacy policy for more info.


Comments

6 responses to “A Quick Guide to the WordPress Transients API”

  1. I actually just started experimenting with transients earlier this week. On a news site that gets (modest) traffic we’ve always had problems with slow loading times. The front page alone runs 4 or 5 separate loops (with images) and when paired with transients we’ve seen a 3 point jump in the page speed. I feel absolutely stupid for not trying transients sooner!

    One question: Initially I only stored the queries but read a few posts about actually storying the entire loops instead, markup and all. Have any insight as to which might be better or worse and why?

    1. Hey Drew. 🙂

      When I work with transients, I find it best to store the results of the database lookups (for example, running get_posts() and then storing the results), rather than storing the actual markup. This means I can freely change the markup without having to worry about the data lookup (essentially splitting the task into the database lookup and the output as separate tasks).

      In some cases, if the HTML processing itself is quite intensive, it may be worth caching the HTML in a transient as well (maybe even a separate transient to the lookup data) and for a shorter time. Even a few minutes cached could make a difference. 🙂

      1. Generally it is a bad idea to store data in a transient that comes from the database to begin with, because a transient is sort of a poor-man’s caching.

        Transients are stored in the database (unless you have a “persistent object cache” set up, in which case they go there). So, it doesn’t really help you much to store data that you got from the database back into the same database only in a different place. It can help slightly if you have large amounts of processing going on, but honestly the benefits are generally small enough for a better approach to be taken.

        If you are having problems with lots of database overhead, a much better long-run solution is to set up a persistent object cache. memcached, xcache, APC, any of these will work. I recommend the W3 Total Cache plugin to let WordPress then use this memory cache for storing objects. This will lower the number of DB queries over the whole site and is generally good enough. If you still need to optimize further, you can then avoid the (minor) overhead of the Transient API and just use the object caching functions directly to store your objects.

        Me and Nacin discussed this somewhat at WordCamp San Francisco 2011. Video is here: http://wordpress.tv/2011/09/07/otto-wood-andrew-nacin-the-otto-and-nacin-show/

        1. Thanks Otto. 🙂

          Yeah, the code example above and the example of an expensive query is more just an example, really.

          I mostly lean towards transients when making requests from an external API or resource that I need to make periodically (ie: exactly as you said… as a poor man’s caching).

          Yeah, I watched the “Otto and Nacin Show” a few weeks back… learned a ton. Thanks man. 🙂

  2. PROTIP: get_transient actually returns “false” for cases where there’s no transient. A check against == “” is actually wrong, because then you can’t store ’empty’ values like zero and such.

    Here’s a better way to get a transient and check it in one fluid step:

    if (false === ($data = get_transient( $transient_key ) ) ) {
    … no data in the transient …
    } else {
    … data in the transient that was not exactly “false” …
    }

    1. Thanks Otto… appreciate the pro tip. 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *