A Guide to Transients in WordPress

As a WordPress developer, you probably already know how important performance is to a successful website. However, understanding transients in WordPress and how they’ll help you optimize your projects can be a little tricky.

Fortunately, when you break them down, transients aren’t all that difficult to understand. As long as you keep a few key guidelines in mind, you should be well on your way to incorporating them into your next WordPress plugin.

In this post, we’ll provide an overview of what WordPress transients are, along with how and when to use them. There’s a lot of ground to cover, so let’s get right to it!

What Are WordPress Transients?

In order to understand transients, it’s helpful to have some basic knowledge of caching and Application Programming Interfaces (APIs). That’s because WordPress transients are a way to cache the information retrieved by APIs. Unlike with browser caching, however, transients store this data in your site’s MySQL database on the server.

Every transient is made up of three parts:

  • $transient. This is the string used to identify your transient and call it up. It’s also referred to as the transient’s ‘key’ or ‘name’.
  • $value. This is the information being retrieved via an API. A transient’s value can be an object, an array, a number, or a string.
  • $expiration. This is how long a transient stays in your database, before it’s deleted and you have to access the information you need through the API again.

On the surface, that’s all there is to WordPress transients. However, in order to use them properly, there’s more you need to know.

The Benefits of Using Transients on Your WordPress Site

As we mentioned earlier, the primary benefit of transients is that they improve website performance. Here’s a rough outline of how that works, using the Google Site Kit plugin as an example.

When the plugin is activated, it uses an API to display data from platforms such as Analytics and Search Console in the WordPress dashboard. Without transients, WordPress would have to retrieve this information from each tool every time you viewed your Site Kit dashboard:

Instead, Site Kit includes transients that cache data from Analytics and Search Console. They are stored for one day (or one hour if the platform returns no data). 

Every subsequent time you access your Site Kit dashboard, WordPress can quickly retrieve the stored information from your database instead of having to call the API again. When the expiration period runs out, the old data is deleted.

This means you don’t have to wait for your results to load every time. This comes in handy in a variety of situations, such as showing social media share counts for your posts or displaying a newsfeed.

When to Use WordPress Transients

Transients are deleted from your database once they reach the end of their expiration period. For that reason, you only want to use them for information that is continuously re-created. 

Additionally, although they can improve your project’s performance, transients are best reserved for large queries and remote calls. If it will require more code to create a transient than it will to simply make a fresh request for the resource each time it’s needed, you’re better off going without.

Managing WordPress Transients

If you want to easily see and manage the transients that are currently at work on your WordPress site, you can install the Transients Manager plugin:

It provides a complete list of transients, which you can find by navigating to Tools > Transients:

Here you can see all three transient elements we listed earlier – the key (name), value, and expiration period. You can edit any of these features by clicking on the Edit link:

You can also delete transients individually or in bulk.

Basic Operations Used in Transients

When it comes to coding your own transients, there are three basic operations you’ll likely need to use. We’ve outlined each of them below, continuing to use Site Kit as an example.

1. Setting Transients

Creating or ‘setting’ transients is the process of defining the key, value, and expiration period, and applying that information to the relevant data. To do so, you’ll use the following format:

Set_transient (‘key’, $value, expiration_period)

Here is the code used in Google Site Kit to set the transient that stores analytics data:

// Cache "data found" status for one day, "no data" status for one hour.
			set_transient( $transient_key, (int) $has_data, $has_data ? DAY_IN_SECONDS : HOUR_IN_SECONDS );
		}

		return (bool) $has_data;
	}
}

The transient key is googlesitekit_analytics_has_data (defined earlier in the code), the value is $has_data or $has_data ?, and the expiration period is one day or one hour (depending on the value).

2. Retrieving Transients

Retrieving transients is a little more complicated. First, you need to use a function to request the necessary data. Then you’ll check to see if it has a corresponding transient that should be loaded, instead of making a new API request.

The result might look something like this:

function some_function(){
	$transient = get_transient(‘key’);

You’ll then need to either return the transient, or delete the expired data and make a new call to the source. Finally, you have to set the transient after you’ve returned the new data, so it will be stored again until the expiration period runs out.

In Google Site Kit, that looks like this:

	/**
	 * Checks whether Analytics data exists for the given URL.
	 *
	 * @since 1.4.0
	 *
	 * @param string $url The url to check data for.
	 * @return bool
	 */
	protected function has_data_for_url( $url ) {
		if ( ! $url ) {
			return false;
		}

    $transient_key = 'googlesitekit_analytics_has_data_' . md5( $url );
    $has_data      = get_transient( $transient_key );

    if ( false === $has_data ) {
        /* @var Google_Service_AnalyticsReporting_Report[]|WP_Error $reports Array of reporting report instances. */
        $reports = $this->get_data(
            'report',
            array(
                'url'     => $url,
                'metrics' => array(
                    array( 'expression' => 'ga:users' ),
                    array( 'expression' => 'ga:sessions' ),
                ),
            )
        );

        if ( is_wp_error( $reports ) ) {
            $reports = array(); // Bypass data check and cache.
        }

        foreach ( $reports as $report ) {
            /* @var Google_Service_AnalyticsReporting_Report $report Report instance. */
            $report_data = $report->getData();
            /* @var Google_Service_AnalyticsReporting_ReportData $report_data Report data instance. */
            foreach ( $report_data->getTotals() as $date_range_values ) {
                /* @var Google_Service_AnalyticsReporting_DateRangeValues $date_range_values Values instance. */
                if (
                    isset( $date_range_values[0], $date_range_values[1] )
                    && ( 0 < $date_range_values[0] || 0 < $date_range_values[1] )
                ) {
                    $has_data = true;
                    break 2;
                }
            }
        }

This code should then be followed by the snippet we included in the previous section for setting transients.

3. Deleting Transients

In some cases, you may find that you want to remove a transient. For instance, if you want to always see the most updated analytics in Google Site Kit, it would be better not to cache data  (although we’re not recommending that you actually delete Site Kit’s transients). 

Otherwise, the plugin will show the same results throughout the day, even if you’ve had new visitors. Since the transient lasts for 24 hours, the data you view in the afternoon will simply be a cached version of the data you loaded in the morning.

The easiest way to delete transients is by using the Transients Manager plugin. However, if you want to use code instead, you can put the delete_transient() function to use. All you need is the transient key:

delete_transient(‘key’);

However, you’ll have to repeat this for each transient you wish to delete.

Transient Expiration: How Does It Work?

Transient expiration periods can be expressed in a few different ways. The simplest two options are:

  • In seconds (set_transient(‘key’, $value, 86400))
  • Using WordPress Time Constants (set_transient(‘key’, $value, DAY_IN_SECONDS))

Alternatively, you can also set never-expiring transients. This can be useful in situations where you want to keep transient data the same, until you manually delete and reset the cached information.

Creating never-expiring transients is quite simple. Simply leave the expiration parameter in the set_transient function blank, or identify it as zero.

Understanding the WordPress Transients API

The WordPress Transients API is simply the means by which information is cached in your site’s database. It enables all of the related operations we’ve discussed throughout this post, including setting, getting, and deleting transients.

In other words, the Transients API is just the part of WordPress’ core that lets you use transients. 

Do More With Your WordPress Site

As a WordPress developer, providing your end users with access to remote data while maintaining fast performance is key. WordPress transients can help you accomplish just that.

However, it doesn’t hurt to get a little extra help from lightning-fast WordPress hosting and professional developer resources. Whether you’re new to coding or a seasoned pro, we’re ready to help. Check out our plans today!

Get started.

Build faster, protect your brand, and grow your business with a WordPress platform built to power remarkable online experiences.