Using the WordPress Transient API

There are a lot of calculations you might need to do in order to make your WordPress site run properly. Things like counting the number of page views or posts, fetching data from a social media site, or maybe even just getting some data from your database. All of these can slow down your site if you have to do them every time the page loads, which makes a less user friendly experience for your visitor.

To solve this problem, we use the WordPress Transient API. It is an API that allows you to temporarily store data that you plan on using again. This data is automatically made available so you don’t need to recalculate it, saving your future page load time.

Setting Up a Transient

Your transient is a key-value pair stored in a database. That means that when you store your transient, it must have a unique identifier (just like an option or post meta data). You’ll also need the data you want to store, and the amount of time you want it to last.

$identifier = 'my-transient-key';
$data       = array( 'data1', 'data2', 'data3' );
$expire     = HOUR_IN_SECONDS; // 1 hour WordPress Constant
set_transient( $identifier, $data, $expire );

As you can see, the expiration value is the number of seconds until the data should expire. WordPress will automatically calculate when the data will expire by adding that many seconds to the current time. After expiration, the transient will be cleaned up and will no longer return the data.

Using Transients in Calculations

Most of the time you’ll use transients to cache data that you want to use often, but happens to be expensive to grab. For instance, grabbing a list of tweets from Twitter might be a process that you only want to happen once a day. You can use transients to do this.

To make sure we are only grabbing the data from Twitter when we don’t already have it in a transient, we are going to fetch the transient using the get_transient() command, and see if it is false. Transients that have never been set or have expired will return false.

$data = get_transient( 'my-transient-key' );
if ( false === $data ) {
  $data = get_twitter_data();
  set_transient( 'my-transient-key', $data, $expire );

You can see, we only fetch the twitter data if the transient returns false. If the transient has data that is still valid, the check will fail and the site will continue rendering using the cached data instead.

Like this tutorial? Subscribe and get the latest tutorials delivered straight to your inbox or feed reader.

Your rating: 1
Rating: 3.4 - 5 votes

Popular Add-ons

Category Icons

Add icons to your ClassiPress categories


Sorted Filtered Coupons

Sorting and Filtered Coupons on coupons listing pages as well as search…


ClassiPress Video Embed

Allow users to embed video from YouTube & Vimeo into their ad listings…