Test Target...

5 Ways to Use WordPress Transients

By Andrew Mull faded laptop in background with html code highlighted on the screen

When it comes to creating custom functionality for a client, Transients are one of the more overlooked tools available to developers.  Here are a few ways to use WordPress Transients as well as an important warning for when not to use them:

1. Caching Expensive Queries

The most obvious use of Transients is also the one WordPress itself uses most often – lightening the load placed on the database. In places like The Loop, WordPress will cache query results for that specific instance of WPDB. But, that information doesn’t persist across different users in different parts of the world.

If different users separately looked at a WooCommerce store to see what was on sale or hit a page that needed to know if the site had multiple authors, the site would have to run those calculations separately for each user. That makes them “expensive” queries because they require more resources from the database. This makes them a prime candidate for Transients, which are a perfect fit for data that multiple users may need simultaneously, but that doesn’t change frequently enough to warrant being calculated from scratch each time.

By using a transient in this case, the system can store the results of that request and only run the expensive query if the cached data is expired or otherwise not available. This saves your server precious processor cycles, which also make page load times faster for your users. Since page speed matters to SEO, using Transients can help you benefit your users and boost your SEO efforts too.

How to Use WordPress Transients for Caching Expensive Queries

To use them in this way, you want to store the Post IDs that result from an expensive query, essentially the returned value of an expensive function as “select […] where ID in (<ids>)” runs much, much faster than a complicated series of joins, unions, and data manipulation once the query is finished.

Like all forms of caching, you always need to strike a balance between bogging down the server and serving stale content. So, be sure to carefully consider “how long is too long” and “how short is too short” when setting expiration times for this kind of transient. Examples of where WordPress uses this method include wp_rand() seed, multisite HDD quota calculations, oEmbed, Theme feature lists, and is_multi_author().

2. Alert Messages in the Admin

This one is a more subtle approach. Instead of relying on the Session, which can expire if the user leaves their window open too long without interacting with the site or relying on Query String parameters in places where redirects are common, WordPress uses Transients to store messages such as “Post Updated”.

This is useful when the system performs a handoff between post-new.php (writing a new post) and post.php (editing an existing post) after pressing either “Publish” or “Save Draft” for the first time. Using a transient in this case allows you to store the content of the message without having to write a long and drawn-out function that parses through what “new-job-success” and every permutation of that snippet may be to figure out which message to display.

Be Careful in Choosing the Transient Name

When using WordPress Transients in this fashion, you have to be careful about how you choose the transient name. In cases like this, it’s a good idea to save some identifying information in the transient’s key, such as Post ID, User ID, or other such items that can be used for denoting who gets the message and who doesn’t.

You don’t want Bob getting a ‘Save Failed’ message, only to be keyed too broadly and make Alice think her post failed to save. Also, it’s a good idea in these cases to clear the transient as soon as it’s displayed, so that stale, unwanted messages don’t linger. Examples of where WordPress uses this method include Options Page submit results, Post save results, and results of “Delete Plugin”.

3. Preventing Redundant Processes and Collisions

This one happens completely behind the scenes. Chances are, unless you’ve been deep in the guts of WordPress, you may have never even noticed it. Whenever something has to be “set it and forget it” behind the scenes, like a task registered to wp-cron processing or regenerating a Media Library item’s metadata, the server doesn’t inherently know what’s still running, what has finished, and what hit a silent failure.

That’s where Transients come in. By tucking a little note inside the database that “Pull from the off-site API” is still running, the system knows not to try again unless so much time has passed there’s a good chance it isn’t still running, but has instead failed in a way that didn’t clear the transient. Keen eyes will notice that “<user> is editing this post. Take over?” isn’t on this list. There’s an important reason for that, which will be covered later.

Most of the time, you won’t need to do this manually because wp-cron tracks it for you. But, if you ever find yourself needing to emulate something similar without actually using it, it’s a good idea to set a transient as the first thing that piece of code does and clear it as the last thing it does. Examples of where WordPress uses this method include regenerating metadata for Media Library items and tracking which wp-cron processes are running.

4. Failsafes

This is one you’ll likely never have to use in a custom project, but it’s clever. As such, it’s worthy of a mention. Have you ever noticed that when you’re using the Theme Editor the whole site doesn’t just crash and burn if you make a syntax error like a missed semicolon, a -> where you wanted a =>, or any of those silly little mistakes we’ve all made and will all make for the rest of our careers? You have WordPress Transients to thank for that. By using Transients in this way, WordPress is able to roll back Theme Editor code changes that would result in a fatal error.

5. Debouncing Calls to Remote Servers

This is another rarity you may never see the need to use. On rare occasion, you’ll need something to run regularly, but not in a separate thread, which makes a wp-cron entry undesirable. It’s a strange edge case as, more often than not, regularly-scheduled items can be trusted to wp-cron and left to their own devices. Still, it’s noteworthy enough to include.

WordPress uses Transients in this way for checking for new “Post by E-mail” posts. Or, more accurately, keeping track of the last time it made that check, so it knows not to spam the mail server with requests during high-traffic periods. You may find this useful for those oddball situations where you’re pulling your hair out because you need it to work like wp-cron without actually being wp-cron.

Maybe it’s a server that doesn’t play nice, maybe it’s hitting a remote API, but doesn’t need to do so in real-time, or maybe it contains something like oAuth that requires the user to explicitly “sign off” on the action being taken – whatever the case may be, WordPress Transients can help manage it.

Warning: Places NOT to Use Transients

It may sound like Transients are like a silver bullet, a catch-all good thing. But, that’s a dangerous assumption to make. The thing about Transients is that they can’t be taken for granted. Transients are, by nature, transient. They are temporary information that comes and goes.  They can be cleared at any time and for nearly any reason, from “it got old and the ‘Clear Expired Transients’ wp-cron task ran” to a user getting overeager with the Transients Manager plugin.

As such, they’re well-suited to situations where it’s convenient for the information to be there, but it makes them poorly-suited to situations where you need the information to be there. This is why WordPress doesn’t store the Post Locks. The aforementioned “Jim is editing this post” modal does not work as a Transient because it could get wiped at any time and now you have a potential collision on the most important aspect of your site – the content. In cases like this, you’ll want to use similar concepts, but in a more permanent locale. WordPress, for example, stores the Post Locks as a hidden Post meta field. When it’s not working with Post data, you could also store something like that in the Options table.

By using these different ways to use WordPress Transients, especially for caching, you can improve your plugin or your website’s performance even under high-traffic situations and even when your user-facing caching is already on-point.

View Comments

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Are You Ready To Discover What Mind Can Do For You?

Click the link below to get started!

Work With Mind