Getting Started With WordPress Transients API

WordPress as a platform evolved over the last decade to become much more robust for developers. But it wasn’t always this way.

In the past, developers implemented most internal data handling logic from scratch. This led to a significant amount of insecure and untested code in plugins and themes — usually copied and pasted from sites like StackOverflow.

Since then, WordPress has introduced some notable additions that standardized developer interaction with WordPress components. For example, Gutenberg completely reworked the way users interact with the Post Editor. The Settings API abstracts the creation and management of custom settings pages, and the Transients API handles the creation and retrieval of cached information.

These changes laid the foundation for WordPress today, positioning itself as a platform that developers can trust to build complex applications — not just blogs.

In this blog, we’ll look at a pair of use-case examples for WordPress transients, understand how each helper function works, go through the most common pitfalls, tips, and tricks, and review some of the most commonly used plugins to manage transients.

If you already feel overwhelmed, we offer managed hosting solutions for WordPress so you don’t have to worry about optimizing your site. We go through exactly what to look for when looking for the best WordPress hosting services, and we also offer guides on how WordPress works so you can better understand the inner workings of the framework and possibly get some ideas about how to best use transients.

What are WordPress Transients?

WordPress transients are essentially cacheable data labeled with a name and given an expiration time (think something like a backend version of a cookie). This data is typically stored in your database (inside the wp_options table), but it can also be configured to leverage a third-party caching solution to store it in your object cache (like Memcached or Redis).

If you want to know more about setting up a third-party caching solution for your WordPress transients, check out this guide on how to enable Redis Object Caching.

What are Transients in WordPress?

So, what are transients in WordPress? One of the most common needs for a caching solution is to store the results of an external API call, and transients provide a straightforward way to achieve that.

If an API request is left uncached, it can quickly become a bottleneck in your application due to unpredictable response times from the API server. Depending on the size of your application, you could also start getting time penalties based on the number of requests per minute your server makes.

WordPress lets you easily manipulate how long a transient is stored and this is how you optimize your application for the traffic it gets. Setting a longer expiration time for an API call can save you a significant amount of potential requests, which also reduces the load on your API server.

A good caching strategy can be a huge factor in improving overall server costs and bandwidth usage. Of course, this all depends on your application’s situation and caching is not the be-all and end-all to fix all load issues in your application.

If you’re interested in implementing more robust caching strategies in your application, check out this guide on how to enable full-page caching for managed WordPress and WooCommerce sites.

We made a very simplified flow chart so you can visualize how WordPress transients work (and caching in general) to help you prevent unnecessary API calls.

Simplified flow chart showing how WordPress transients work

This process begins the moment your application decides it needs to retrieve data from an API. When there is no transient, the API request is triggered and as a result it gets stored in a new transient. The next time your application starts a request, the transient will exist and it will contain the same data that was returned by the API originally. You just saved your first few bytes in bandwidth! 🎉

Another common use case involves storing the results of a complex call to WP_Query or any of its alternatives (like get_posts). As before, we made a very simple flow chart so it’s easy to visualize how WordPress transients fit into many scenarios.

Another simple flow chart to visualize WordPress transients

The process is the same. It begins whenever your application needs to do a process that uses the database. If a transient has not been created for the query, then the query will be made as usual but the results will get stored in a new transient. The next time your application needs to do an equivalent query, the transient will already exist and contain the same data returned from the original query.

As a result, we can make the flow chart even more simplified to help visualize how you can add WordPress transients to your application effortlessly.

How to add WordPress transients to your application

Implementing WordPress transients improves the end-user experience by not having to wait for information to be retrieved. Not only do you end up saving money, but you also generate more because faster loading times in your application often lead to better organic traffic from search engines.

How to Use WordPress Transients

WordPress includes three methods to deal with transients depending on the environment your application is working with. In no particular order, here is the full list of WordPress Transient API public methods:

  • set_transient( $name, $value, $expiration )
  • get_transient( $name )
  • delete_transient( $name )
  • set_site_transient( $name, $value, $expiration )
  • get_site_transient( $name )
  • delete_site_transient( $name )

The site_ variations are available for use within a WordPress Multisite environment, but they’re functionally the same as their non-site variants.

A WordPress transient needs three parameters:

1. name: A unique identifier for the data being stored.

2. value: The data you want to store.

3. expiration: The time in seconds until the data should expire. This defaults to 0, but for transients to be effective this should be greater than 0.

The only time you need to know all three parameters is when you’re creating the transient. After that, you only need the transient’s name to retrieve or delete the data.

Fetch the WordPress Transient

Next, we’re going to show you a real-world example of how these flow charts would be implemented in PHP. We’ll focus on explaining the logic around working with transients, and how to get started using it today. Don’t worry if you don’t understand some of the code you’re going to see. We’re not interested in how the data is constructed. It’s only there to show some real-world context around WordPress Transient API methods.

To retrieve data from a transient, all you need to know is the transient’s name. The function we’re looking for is get_transient, or get_site_transient if you’re on a WordPress Multisite environment.
...

$price = (float) get_transient( 'product_183_price' ) ?: 300.0;

$name  = (string) get_transient( 'book_345_name' ) ?: 'John Doe';

$variants = (array) get_transient( 'product_183_variants' ) ?: [];

...

In the first line, we’re creating a price variable by casting the result of get_transient to a float type. If the transient doesn’t exist, a default value is used. This happens because if a transient does not exist, does not have a value, or has already expired, the returned data will always be a boolean false.

The ?: symbol in PHP is called the ternary operator and is a simplified way of writing an if statement, where the value after the operator becomes what gets returned in case the previously compared value is false.

The other two lines are there to demonstrate how any type of value can be used for transients. We’re casting a name variable as a string, and a variants array that would contain a list of information. Almost anything that can be assigned to a variable can be stored as a WordPress transient (more on this later).

Remove the Saved Transient

Removing transients is often reserved for data that depends on something else that is being or has just been removed. For example, if you keep track of a person’s scorecard in a game but they decide to stop playing, tracking that scorecard is no longer needed.

... delete_transient( 'soldier_76' );...

Deleting a transient is beneficial if your application is constantly creating and removing things, but a transient gets automatically deleted after the expiration time passes — more on this later. You may also want to delete a transient manually when instead of waiting for the transient to expire, you can simply clear the transient cache to force getting a refreshed value again.

Save WordPress Transients

To save a transient, you need to name it, assign it some data, and set an expiration time in seconds after it’s been created. The data you assign doesn’t have to be treated in any way, and the only requirement is that the value is serializable. If you’re unsure what this means, don’t worry. Most common variable types are serializable by default. The data doesn’t need to be SQL-escaped either — this is all handled by WordPress for you.

...

$response = wp_remote_get( 'https://example.tld/subscribers' );

set_transient( 'subscriber_count', $response['body'], HOUR_IN_SECONDS );

...

In this example, we’re storing whatever is coming from the GET request. We could have also stored the full response variable too because it’s just an array, but a good practice is to reduce the amount of information we’re storing in our cache, so you only store what you actually need.

We’re using HOUR_IN_SECONDS. This is a very helpful constant defined by WordPress that you can use anywhere within your plugin or theme. Here’s the full list of time-related constants you can use:

  • MINUTE_IN_SECONDS
  • HOUR_IN_SECONDS
  • DAY_IN_SECONDS
  • WEEK_IN_SECONDS
  • MONTH_IN_SEONDS
  • YEAR_IN_SECONDS

Please be aware that these are defined as approximations — DAY assumes 30 and YEAR does not take leap years into account. If you need precise information, consider using DateTime or Carbon.

If you want to know more about the default constants defined by WordPress, check out the default-constants.php file at the official WordPress GitHub Repository

WordPress Transients Expiration

The expiration time is very important for WordPress transients to work as a caching solution, because otherwise the transient will be stored forever. That would make it essentially just a regular option, which has its own API. Transient expiration is needed so WordPress can automatically delete the transient after it expires.

This is not completely automatic because the transient will not be deleted as soon as it expires. Instead, it will be deleted the next time your application is loaded after the transient has expired. This is a limitation on how scheduled jobs work in WordPress. Because it is a PHP application, it can only be executed whenever an HTTP request is made to the server.

One way to work around this limitation is by creating a cron job that runs at a system level and using the WP CLI to delete expired transients, but this would be a topic for another article.

This limitation, however, should not deter you from using WordPress transients. Because the transient purge process happens before your plugin or theme code runs, it isn’t critical that the transient is technically still there after it expires.

Here’s the final code snippet where you can see how everything comes together. This is the code representation of the flow chart we explored before.

...

$subscriber_count = get_transient( 'subscriber_count' );

if ( $subscriber_count === false ) { # Transient does not exist or has expired.    $subscriber_count = 5;   

set_transient( 'subscriber_count', $subscriber_count, MINUTE_IN_SECONDS * 60)}

...

For this example, we did not set a default value for subscriber_count because we want to know if the return value is false to regenerate the transient.

The first time your application runs, the subscriber_count will be false because the transient hasn’t been created. Then it will enter the condition block, re-assign the same variable, and store it.

The second time your application runs, the subscriber_count transient will exist. That’s what will get returned instead of false, avoiding the conditional and continuing your application’s logic without any major refactor. We’re reusing the same variable name, so we can trust that it will eventually have the data we need.

Pitfalls and Tips for Transients

Transients aren’t supposed to be a be-all-end-all solution. If your application has to deal with data that always needs a fresh response, you shouldn’t use transients to speed it up. Transients are best used for data that is shown multiple times across the site or data that doesn’t change very often.

If you’re using your database as the storage for WordPress transients, there is a 172 character limit on the name. This is because WordPress will automatically inject some keywords to the name you pass to keep track of it.

The value you store in a transient can be almost anything, but it’s recommended that if you need to store a boolean value inside a transient, you convert it to an array or an integer value using constants or enums. This is because we need to check for false to know if the transient exists or not, so storing a false value would cause very difficult debug issues.

Plugins for Dealing with Transients

Transients Manager provides you with an easy user interface to manage your transients. You can search, edit, and delete transients and even suspend transient creation to help with testing and debugging. The only caveat for this plugin is that it only works if you’re using your database for storing transients, so this is generally used as a local development tool only.

Query Monitor is a plugin that among many things can show you which transients are active and which transients were updated during your last HTTP request. This is a very powerful plugin that can be used for local development, or to debug performance issues.

Delete Expired Transients is a plugin that does what it says. It will add a new scheduled job in your WordPress installation to remove any transient that is still lingering after it has expired.

Try WordPress Hosting With Nexcess

While this all can seem daunting, now you know what transients are in WordPress and how and when to use them. After all, they are an indispensable tool for your WordPress application.

If your application is starting to grow and you feel that implementing WordPress transients will not be enough to improve your site’s performance, it may be time to upgrade to a fully managed WordPress hosting solution.

At Nexcess, we offer a 30-day money-back guarantee because we’re sure you will love it, or we’ll issue a refund if you don’t. Check out our WordPress hosting plans to get started today.

This blog was originally published in August 2020. It has since been updated for accuracy and comprehensiveness.

Roberto Gongora
Roberto Gongora

Roberto lives in Barcelona, Spain and has been programming websites since he was 12 years old. Video game soundtracks are his favorite type of music. He loves cooking and gardening just as much as he love computers and tech.

We use cookies to understand how you interact with our site, to personalize and streamline your experience, and to tailor advertising. By continuing to use our site, you accept our use of cookies and accept our Privacy Policy.