Getting Started With The WordPress Transients API, Part 1

Getting Started With The WordPress Transients API, Part 1

Tutorial Details
  • Program: WordPress
  • Version (if applicable): 3.2.1
  • Difficulty: Easy
  • Estimated Completion Time: 30 minutes

One of the nicest things about working with WordPress is the power of its API. When creating themes and/or plugins, the platform makes it incredibly easy to serialize and retrieve data. In fact, the API abstracts many of the common challenges of working with data such as data sanitization and efficiently retrieving data on request. Throughout the next two post, we’ll take a look at the Transients API, why it matters, how to use it, and take a look at a practical implementation that we can use in future projects.

Generally speaking, all of the above is accomplished with the WordPress Options API which is great for saving, updating, and reading options, but if you’re working with a large set of data the Options API may not be providing the most optimal performance possible. Specifically, you may be able to improve the overall performance of your work (and its extensibility with other software) if you were to take advantage of the Transients API.


What Is The Transients API?

Simply put, the Transients API provides a way to store information in the WordPress database with an expiration time. When saving information using the Options API, values are stored using a key and a value.

For example, say that you’re working with a plugin that saves your Twitter username in a custom field named ‘Twitter.’ You can conceptualize the way WordPress saves this information may treating ‘twitter’ as the key and your username (say, ‘MoreTom’) as the value.

The difference in the way that the Transients API saves it’s information is that a third piece of data – an expiration time – is saved to the database. This is key for speeding up performance namely with caching.

Additionally, data saved via the API (called transients) is leveraged by caching plugins and caching software whereas standard WordPress options are not. For example, when you store a value using the Transients API, caching software – such as memcached – will instruct WordPress to store values in such a way that it can easily retrieve it on each page request rather than hitting the database each time.

Cool, huh?

The caveat is that since transients have an expiration time, they aren’t guaranteed to be database so we should make sure that the values that are store are ones that aren’t critical to the theme or plugin’s success (although there is a way to manage this that we’ll check out in the next post).

The most important thing to remember is that you don’t want to store every option value using the Transients API. A good rule of thumb is store the values that are often most expensive and that aren’t required for page loads.

As useful as understanding the API really is, the real advantage comes in actually using it.


Using The Transients API

The nice thing about the Transient APIs is that it’s extremely well implemented with three functions two of which you will use regularly. The three main operations for transients are setting values, getting values, and deleting values.

Set A Transient

Saving a transient requires three specific pieces of information:

  • The key that will be used to retrieve the value
  • The value to serialize
  • The amount of time (in seconds) to store the data before refreshing it

The signature of the method is as follows:

  • set_transient($key, $value, $expiration);

Easy,right? A simple example for calling this function would be as following:

	set_transient('twitter', 'MoreTom', 60 * 60 * 12);

Get Transients

Retrieving a transient is even simpler than setting. In fact, it’s very similar to retrieving a options from the WordPress Options API. All you need to know is the key that was defined when you set the value.

The signature of the method responsible for returning the value is:

  • get_transient($key);

In following with the example above, we’d retrieve the user’s Twitter username by calling:

	get_transient('twitter');

Simple, huh?

Deleting Transients

Setting and retrieving transients are the two most commonly used functions of the API, but there are times during which you may need to remove a value before the expiration time has been reached.

In that case, you can take advantage of the delete_transient function:

  • delete_transient($key);

Similar to retrieving a value, you simply pass the key used to identify the transient value to the function:

	delete_transient('twitter');

The function will return true if the value is properly removed, false if the value was not removed or if the deletion of the value didn’t work correctly.

Obviously, the performance benefits pay dividends in comparison to how difficult it is take advantage of the API. Perhaps the most important thing to remember is that you don’t want to store every option value using the Transients API – only those that are the most expensive and that rarely change.

In the next post, we’ll see a practical implementation of the API by creating a plugin that takes advantage of the API.

Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • EmpreJorge

    This is the first time i hear about transient, it looks really nice.
    i’ll be waiting for the next part :D

    • http://tommcfarlin.com Tom McFarlin
      Author

      Awesome! The next post includes an actual practical use of the API so hopefully it’ll be a good example of how to take advantage of the API :).

  • http://www.paulund.co.uk Paul

    Transient are vital when working with APIs. Most APIs have a limit on how many requests you can make per hour. Transients are a great way of getting around this problem.

    • http://tommcfarlin.com Tom McFarlin
      Author

      Exactly – perfect example of how and why to use them. Thanks Paul!

  • http://www.customicondesign.com/ custom icon design

    Like EmpreJorge, this is also the first time to hear the transient. and never used before. SO I think WP is so deep that I will work harder to keep it on.

    • http://tommcfarlin.com Tom McFarlin
      Author

      Awesome – good luck!

  • http://dougal.gunters.org/ Dougal Campbell

    You might want to clarify your statement about using transients for data that “aren’t required for page loads.” Because speeding up page loads by using transients is often the point. :)

    You want to use transients to store data that:

    1. Is expensive to calculate or fetch
    2. Is time-sensitive or changes over time

    Of course, extrapolating from your article, a good example is “my recent tweets”. You don’t want to fetch the same data over and over again on every page load, because it’s extra work to get it from the Twitter servers (expensive in page-load speed and server cpu/network resources), and it generally only changes every few hours (in most cases).

    So you fetch once, store the data locally as a transient with an expiration time of say, 2 hours, and use the cached version until it expires.

    • Dj

      Thanks Dougal … I had to read down the comments to realize what he was meaning by saying “expensive” – twice. Also, it seems to me if one is too lazy to multiply out the seconds by hand and hard code them it sort of defeats the whole purpose of caching in a transient.

      • http://tommcfarlin.com Tom McFarlin
        Author

        DJ,

        Certainly didn’t mean to be confusing by using the word expensive.

        And it’s not a matter of being ‘too lazy to multiply out the seconds,’ that’s more of how I opted to write the code. The function accepts seconds and I want to indicate, say, hours then it’d obviously be 60 seconds, 60 minutes, 12 hours. I also agree that 43200 would work just as fine :).

        Thanks for the comments!

    • http://tommcfarlin.com Tom McFarlin
      Author

      Yes – sure. Thanks for this clarification, Doug.

      Perhaps a better way of stating would be that it’s okay to store data that is required for page load, but make sure that it’s written in such a way that if the transient has expired then the data is requested from whatever source; otherwise, the page will block.

      This is actually covered a bit more in the next article.

      Either way, definitely appreciate it :).

  • http://webania.net Elvin

    Very interesting tutorial, thanks to the author.
    I have a question.
    How suitable is to use this transients instead of $_SESSION variables of PHP?
    It is possible its clear, but how may it behave itself with system, will be any trouble?

    • http://tommcfarlin.com Tom McFarlin
      Author

      It’d really depend on how you actually implement the $_SESSION functionality, but Transients are built into WordPress, are stored in its database, and are subject to the rules of its API.

      $_SESSION, on the other hand, is more of a pure PHP concept and would require that you do a lot of session handling and serialization on your own.

      I don’t really see how they’d conflict unless you were doing some sort of mixing of the two (such as trying to store transients in session or the session as a transient ;).

      Hope this helps!

  • Pingback: Links der Woche 1 | ITWS Developer Blog

  • Pingback: A Free wordpress newsletter » Theme.fm Weekly Roundup #7

  • http://www.seslikirmizi.net seslikırmızı

    It’d really depend on how you actually implement the

  • Pingback: Getting Started with the WordPress Transient API, Part 2 | Wptuts+

  • Pingback: My Stream » Getting Started with the WordPress Transient API, Part 2

  • http://unrelatedmedia.ca Neil Davidson

    Thank you for bringing this to the community. I had seen the use of transients in various plugins but never really thought about looking it up.

    For the average blogger use of transient is a little pointless. However, for large and dynamic websites using things with (semi) real time data for twitter, facebook, digg, etc then it becomes a very powerful tool.

    What transient does is take from a very simple MySQL concept for creating a temporary database for frequently used queries on large chunks of data. Transient just does it the WordPress way.

    For ease of understanding think about this: You have a e-store selling over 250,000 varieties of widgets, 100,000 do-hickies and 20,000 thingies. You have great website traffic and thousands of people are searching your products like crazy! They are often using the same searches:

    Widgets
    do-hickies
    thingies

    And all of the products are in a well designed database using several tables, primary keys, and all the good stuff required of a proper database structure. But it still takes forever to search for things – especially when 400 people are searching as well. Each person is searching the tables

    products
    location
    inventory
    vendor
    work_order

    So we build in a way for SQL to only have to search a single table in the database and we make the table temporary because, with so many products, sales and colors and other things change all the time.

    MySQL Saves the results of the most common searches into their own temporary database which is set to delete after 24 hours (and then recreated with any new content). Now the database only needs to search the table temp_widgets when searching all the widgets. Far better then having to search through every type of product, their associated data tables and filter based on “xxx-criteria-xxx”.

    I’m sure someone else could give an even simpler example but I hope this clears up the purpose of transients better to beginners.

  • Pingback: How to Create a Recent Tweets Widget | How to Web

  • Pingback: Interacting with WordPress' Plug-in & Theme API | Wptuts+

  • Pingback: Interacting with WordPress’ Plug-in & Theme API | Wordpress Webdesigner

  • Pingback: Interacting with WordPress’ Plug-in & Theme API | Shadowtek Hosting and Design Solutions

  • Pingback: Interacting with WordPress’ Plug-in & Theme API | How to Web

  • Pingback: Twitter Trends Widget for WordPress | Wptuts+

  • Pingback: Twitter Trends Widget for WordPress | Wordpress Webdesigner

  • http://twitter.com/InnerBot Greg Johnson

    Hey Tom,
    I believe this will be the 3rd or 4th post of yours this week that has held the answer to my WordPress Questions… Thanks for all the awesome, and keep it comin!

  • http://www.facebook.com/mittul.chauhan Mittul Chauhan

    this is a damn good article man…