Transient API

The Transients API is a WordPress feature that I had never heard of until a few weeks ago, when I wrote a post on getting your Twitter follower count in plain text.

On that post, Otto left a comment with a different way of getting the same result, using the Transients API. Instead of using cron, which can be complicated, transients allow you to use just one or two lines.

In this post, I want to show you how to use transients, and to do that, we’re going to build a simple script that will list the latest commenter on your blog, along with their avatar. The end result will look like the image above.

So What Is a Transient?

To take a definition from Google, we get “one who stays for only a short time”. A transient in WordPress is a piece of information that lasts only for a certain period of time, and is then replaced (updated).

That means these will be things that change regularly, e.g. your subscriber count, or the latest headline in an RSS feed.

The benefit of using transients to store this information is that you can specify how long to leave between updating the data. That way, instead of running your check every time a page is loaded, you can check it once and store that value for everyone to use until you’re ready to check again.

So now that you know why we’re using transients, let’s build our script!

1 – The Latest Commenter Function

In functions.php, go to the end of the file and begin a new function.

1
function pbd_latest_commenter() {

Now let’s define a few settings for our script. Paste the following right below the line you just entered:

1
2
3
// Configuration
$transName = 'pbd-latest-commenter'; // Name of value in database.
$cacheTime = 15; // Time in minutes between updates.

The first value is relatively unimportant. It’s just the name that our data will be stored under in the database, so feel free to name this anything you like, so long as it’s unique (As an aside; the value may not always be in the database. Read the codex page for more info).

The second value is the length of time (in minutes) to leave between each update.

2 – Setting and Getting Transients

The next part of our function is where we will make use of the 2 main transient functions; set_transient and get_transient.

We’ll begin by checking if a transient value has already been set. If it has, we will use that value later, but if it hasn’t, we need to set a new one first.

Paste the following below the lines you’ve already added:

1
2
3
4
5
// Do we already have a saved commenter?
$comment = get_transient($transName);
 
// If not, lets get one.
if($comment === false) :

The code above simply uses get_transient to see if a value already exists, and if it doesn’t, then we’ll start an if statement to get a new value to replace it.

To replace it, we need to get the latest comment from the database, get the avatar that goes with it, and store them both in a new transient. Here goes:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
$commentArray = get_comments(array(
		'status' => 'approve',
		'number' => 1));
 
// Get the avatar for this comment.
$av = get_avatar($commentArray[0]->comment_author_email, 40);
 
// Combine the comment we need, with the avatar.
$comment = array($commentArray[0], $av);
 
// Save our new transient.
set_transient($transName, $comment, 60 * $cacheTime);
 
endif;

The code above does the following:

  • Get the latest approved comment from the database.
  • Use the email from this comment to get the appropriate Gravatar image.
  • Store both the comment object and the avatar in an array.
  • Save this array as the new transient.
  • End our if statement.

The set_transient() function takes 3 arguments. The first is the name of the transient (Which we defined in our configuration at the start). The second is the value to store (The array we just made). And the last is the time in seconds to store it for (Which we’ve converted to minutes for ease of use).

Now all that remains for our function is to return the value of $comment (Whether it was taken from the transient, or freshly gotten).

1
2
3
// Now send back the result.
return $comment;
}

3 – Displaying the Commenter

The last step is to take the values we have just retrieved, and use them to display the commenter’s name and avatar.

In sidebar.php, find the place you want to list the commenter and enter the following: (NB – If you’re using widgets, use a plugin like Exec-PHP to allow you to enter this code in a text widget).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?php
// Get our latest commenter.
$comm = pbd_latest_commenter();
if(!empty($comm)) : ?>
	<li>
		<h3 class="widget-title">Latest Commenter</h3>
 
		<p class="pbd-commenter">
			<?php echo $comm[1]; /* Avatar */ ?>
 
			<a href="<?php echo $comm[0]->comment_author_url; ?>">
				<?php echo $comm[0]->comment_author; ?>
			</a>
		</p>
	</li>
<?php endif; ?>

This code calls our latest commenter function. If we get a value back from that, we will create the widget.

In this case, I’ve just created a simple heading, with an image and the comment author’s name and link in a paragraph. You have the full $comment object stored though, so you could list part of the comment if you chose ($comm[0]->comment_content).

If we don’t get a value back, then nothing is output.

NB – I set this up using the default 2010 theme, where the sidebar is a list. You may need to change the HTML to suit your theme (e.g. to use a <div>, instead of an <li>).

Finally, let’s add some styles to style.css:

1
2
3
4
5
6
7
8
9
10
11
12
13
.pbd-commenter {
	height: 40px;
	line-height: 40px;
	position: relative;
	padding: 0 0 0 50px;
	margin: 10px 0;
}
 
.pbd-commenter img {
	position: absolute;
	top: 0;
	left: 0;
}

With those styles in place, the image will be aligned to the left, with the text vertically centered and a 10px gap between the two.

And that’s it finished. Now your latest commenter is listed in the sidebar without having to run the full comments query and ping gravatar every time.

Hopefully you’ve now seen just how easy the transient functions are to use. To complete that knowledge, you can also delete a transient (e.g. to force it to refresh) using the following line:

delete_transient($transName);

Let me know what you thought of this tutorial, and if you have any questions, feel free to ask them in the comments!

(PS – I love that even after years of using WordPress, it keeps on surprising me with new things it can do, thanks Otto!)

Enjoy this post? You should follow me on Twitter!