Use the Transients API to List the Latest Commenter
51The 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!
Whoa, that’s awesome. I’d never heard of Transients either.
You had great timing on this one Michael. Transients are the answer to a problem I’ve been facing with a recent plugin :D
Haha, glad to hear I’m not the only one that hadn’t heard of them! Definitely a useful feature, but don’t seem to be commonly known.
Thanks for helping to get the word out.
Very interesting :) But now I’m wondering if this message will appear at the top of this page, or will I have to wait 15 minutes! You could have a little feature in a column ‘Recent comments’ and maybe have 3-4 transients and also stored the URL of the page the comment is placed. I’m going to have a little experiment ;) Thanks
A good idea would be to cache it for a very long time and then delete the transient on the submission of a new comment. This way we only need to regenerate when it actually needs to be.
It could make a severe difference in cases where it requires a lot of complex code. Some time back I built up a widget which shows up the most viewed blogs in bar format for a multisite setup.
Sure thing, you could definitely do that. It would be pretty straightforward to do too. You’d just need to hook the delete function in as necessary. Something like this should work:
function refresh_on_new() {
delete_transient(‘pbd-latest-commenter’);
}
add_action(‘comment_post’, ‘refresh_on_new’);
You can simplify code somewhat by getting a transient and checking for false all in one step.
if (false === ( $value = get_transient('name') ) ) {
// transient is false, refresh value and set_transient
}
return $value
It’s a bit simpler and faster. This works because the assignment operator (=) returns the value being assigned, so you can both set and check the value all in one fluid motion.
Note: For long-term transients, using the Options methods is actually slightly faster (two less queries)… unless you’re using a persistent caching solution (like memcached), in which case transients are way faster. So the proper use of transients is really for anything which a) you can refresh through other means and b) for anything you want to expire within a reasonable timeframe. If the timeframe is long, and you know you’re not using persistent caching, use an option instead.
Nice tip!
Thanks Otto, that’s really nice coding form. I’ll remember for that for future use in general, not just here!
And thanks for sharing more information about the mechanics of the two underneath. I was wondering about that when I replied to Ashfame’s comment. Good to know which would work out faster!
This is helpful post. I spent whole day of debugging. Thanks
Wow again. Thanks for the writeup. Just a year ago, I wanted to make a theme. A simple theme, just so my site would look pretty, and match my style. Since that time, thanks in large part to this site (and several others) my theme has grown into this large, complicated beast. Not bad complicated, it just does so much. I love it to be honest….. I just keep learning! So thanks for giving me a new toy to play with!
Thanks, it’s really great to hear that you’ve learned so much from here (And others. Definitely a lot of great WP sites out there :D ). It sounds like you have the perfect way of learning. Trying things out and building something for yourself is always going to be the best way of picking up things like this!
Excellent tutorials @Michael. I love it an trying to apply to my blog soon. Thanks
Judging from your avatar, aren’t you a little young to have a blog?
lol craig, i was thinking the same thing.
Nah, he’s old enough
Your looking at the new CEO of WordPress…. lol
test
Nice!! Might try this one out. Nice tip too Otto!
Thanks
didn’t know about transients, look forward to apply this, thanks for sharing it
Thanks for helping.. Thank you.
THANK YOU Michael! Finally – I have been looking far and wide for this and this is the first one that works!
… i never heard this word :D.nice post ..thank you. ;)
I have never heard of it either but sounds very interesting and will try to implement it. Great job!
What happened to an article every week, Michael!?
I had never heard about the Transients API before, I think we could use it for other things too. It seems it can save a lot of code and time if implemented correctly.
information is very good and very helpful…..thanks
I’m a newbie to blogging, but this sounds like something I’ll have to look into further. Thanks for showing the script.
I was googling to help fix this problem. THANKS!
Hoho, I’d never heard of Transients either.
Happy New Year 2011 to everyone!
Nice post Michael :) I was looking for this. I’m enthusiastic to apply on my blog soon.
This is for a fact, you’re a great webdeveloper. I will try to apply this on my blog.
Just now tried this code in on of my blogs. Worked perfectly. Cool hack.
Thank you for your article is wonderful
We could also use this on other applications. It saves a lot of time in coding development
Your article is interessting again.
Nice tutorial, thank you for sharing.
Useful post
Thanks a lot!
So with the set_transient you store the value in the servers memory?
Nice tutorial, thank you for sharing.
This is awesome, and works like a charm. Question: is it possible to show this value on a per-post basis, rather than for the whole blog?
Question: is it possible to show this value on a per-post basis, rather than for the whole blog?
Great. Never heard of transients before!” Jason Arnott Jersey Thought i had a pretty good oversight over the WP framework by now – Cool to see new features I havent seen before :)
Thank gosh, I was looking for this everywhere! Thank you! I haven’t dealt with transients before obviously ;]
Clay Matthews Jersey Wow, you’re like a professional writer, I love your blog.
Tom Brady Jersey i agree with you , but i ‘m not sure if i can appear
Arian Foster Jersey is a good choose
,I keep on reading this attractive blog.
Guys sports shoes or boots have got any period of nike jordan heels time historical past. Several popular brand names almost all generate Guys collection since importance. It really is tough to be able to indentify what exactly is different inside of among sports shoes or boots, yet between numerous goods Nike and also Adidas are usually finest. Nike Mercurial Talaria / FG will be a couple of baseball shoes or boots designed to use light teijin man made buckskin regarding substantial basketball sense. Contoured velocity previous together with evp midsole.
forex community enjoyed reading your article.
These are pertaining to employ during the entire the summer months a few months, excellent simply because they take in air correctly and thus ignore air when it’s possible to apply it pertaining to complete the task along with amusement, along with never ever way too scorching. Who wants to shell out regardless of Philip Rivers Jersey whether full price help save by simply buying throughout enormous majority. The retail price stages are generally consequently minimal you obtain a pair of tops even more to the price anyone normally spend on a new full price price tag. There are many involving versions which have been offered, a lot of these people will be paid for for all those hundreds of ready and a few people are generally led specially for females. The application of FOOTBALL jerseys are generally amazingly widespread. It is just a approach to meet up with brand-new folks, way too. Information on the continent are generally comprehensive unknown people a new look, a new jerk, enhance your current specs along with horns, when they discover people using chosen hat.