Using WordPress transients to cache data can help to speed up your site’s performance significantly. But how do we use them? Let’s discuss it in this post.

Before I took the software job I’m currently at, I underwent a number of interviews. In doing so, I had this question asked:

“If you had multiple queries being called on the homepage in WordPress, and it was causing a slow load time, how would you go about speeding this up?”

I really didn’t have a strong answer, so I said the magic words, “I don’t know what I would do, yet, without actually seeing the issue in person. What’s the answer?”

He replied, “Transients.”

Caching the queries with transients!

Okay. Honestly…..never heard of them.

So I went and learned all about WordPress transients.

What are WordPress Transients?

WordPress transients are simply a way to cache information temporarily in the database. There are three components: A key ( a string representing the name of the transient ), value ( the content you are storing in the cache ), expiration ( the lifespan of the transient ).

These are stored, for their lifespan, in the wp_options table.

There are three main functions involved:

  1. set_transient(). To save a transient you use: set_transient( $transient, $value, $expiration ); $transient is a string representing the name of your transient. This can be anything, but choose a helpful name. $value is going to be a variable representing your data. $expiration will be the time before your transient expires. See below for helpful constants.
  2. get_transient(). To retrieve a transient you use: get_transient( $transient );
  3. delete_transient(). To delete a transient, you use delete_transient( $transient );

And that’s it!

Give me an example

WordPress transients are really useful for resource-heavy database queries, and can significantly help to cut this number down. You can use the Query Monitor plugin to see this number before and after the transient is set.

But here’s a simple example of how it can be used (note the comments):

// Check if the transient exists
$recipes = get_transient( 'my_recipes' );

// If the transient does not exist, then run the query and set the transient for the $recipes query. The next time this query is run, $recipes will exist as a transient and will not run a new query, but use the cached query instead.
if ( false === $recipes ) {
    $args = array(
        'post_type'   => 'recipe',
        'post_status' => 'publish'
    );

    $recipes = new WP_Query( $args );
    
    // Sets transient for one day duration
    set_transient( 'my_recipes', $recipes, DAY_IN_SECONDS );
}

// Note how only the query above is set as a transient. We want to cache the query. No need to cache the loop.
if( $recipes->have_posts() ) {
    echo '<ul>';
    while( $recipes->have_posts() ) {
        echo '<li><a href="' . get_permalink() . '">' . the_title( '', '', false ) . '</a></li>';
    }
    echo '</ul>';
}

Expiration Constants for WordPress Transients

Here are some “WordPress native” constants that you can use for expiration times:

MINUTE_IN_SECONDS  = 60
HOUR_IN_SECONDS    = 60 * MINUTE_IN_SECONDS
DAY_IN_SECONDS     = 24 * HOUR_IN_SECONDS
WEEK_IN_SECONDS    = 7 * DAY_IN_SECONDS
MONTH_IN_SECONDS   = 30 * DAY_IN_SECONDS
YEAR_IN_SECONDS    = 365 * DAY_IN_SECONDS

An Important Note

Always have a fallback to the transient. The Codex states “it is possible for the transient to not be available before the expiration time. Much like what is done with caching, your code should have a fallback method to re-generate the data should the transient not be available.” This is why we check to see if it exists first. If for some reason it is not available, it will run the query again. No prob.

Delete WordPress Transients When Saving/Updating/Deleting a Post

When you make a change in a post that is using a transient, you want to see that change, right? Thus, you should delete the transient (it will set again) when making changes so those changes reflect.

WordPress has a few hooks we can use for this. Using our my_recipe transient example, we can delete when saving a post or deleting a post (and wherever else you’d want to use this).

function delete_my_recipes_transient() {
    delete_transient('my_recipes');
}
add_action( 'save_post', 'delete_my_recipes_transient'  );
add_action( 'delete_post', 'delete_my_recipes_transient'  );

Manage your transients

There is also a nice plugin to see all the transients on your site and data about them (such as expiration, etc), called Transients Manager. Also, look at the Query Monitor plugin to monitor your performance pre and post-transients.

Conclusion

If you have multiple queries on a page or have some intensive queries that are causing performance issues for your site, then definitely look into implementing transients on your WordPress site.

Travis Rodgers

Buy Me a Coffee at ko-fi.com

Hi, I'm the Travis in Travis.Media. I'm a self-taught software developer, blogger, and YouTuber, sharing everything I'm learning along the way.

Show comments