Caching WordPress Queries for Faster Page Loading

I was reading a few days ago a great post that was talking about the WordPress transient API. If you don’t know what this API is, well you should! In a few words, transients are values that are temporarily stored in the WordPress database, just during the period you decide to conserve them. That’s a really powerful method to store data that you need during a certain period and that then auto-destruct. I thought it should be great to use the transient API to cache queries to speed up your pages loading. Let’s see how.

Setting-up transients

First of all you need to see how to create a transient. There’s a function called set_transient(). This function accepts 3 parameters:

  • $transient – It’s the transient name, expected to not be SQL-escaped. Should be 45 characters or less in length
  • $value – Nothing more than the transient value
  • $expiration – (optional) This is the time until expiration date in seconds

You can use this function nearly every file of your theme or any file of your plugin. If you are not sure where to place it, just put it in your theme functions.php file.

Retrieve transient values

Once you created a transient, you have to use get_transient() function to get the transient value. This function only has one parameter:

  • $transient – It’s the transient name (equal to the first parameter un set_transient() )

This function will return the transient value, and if the the transient isn’t set or the transient is empty, returns false.

Here is a bit of code you can use with get_transient():
if(false === ($data = get_transient($transient_name) ) ){
// Transient does not exist or has expired and $data must be set
} else {
// $data has been set and is populated with the contents of the transient
}

Delete Transient

You can manually delete a transient by using the delete_transient() function, this function accepts only parameter:

  • $transient – It’s the transient name (equal to the first parameter un set_transient() )

Only use this method if the stored value isn’t valid anymore, because as you understood, the goal of the transient is to self-destruct one the specified period expires.

Caching a WordPress Query with Transients

Now that you know how transients work, here is an example you can use to cache a query. The main aim of this method is to speed up your pages loading time by caching recurrent queries. Here is a working code:

// Check if the transient value exists
if ( false === ( $my_query_results = get_transient( 'my_query_results' ) ) ) {
// The value isn't set, so let's create it for a "one day" period
$my_query_results = new WP_Query( 'cat=1&post_type=my_custom_post_type' );
set_transient( 'my_query_results', $my_query_results, (60 * 60 * 24) );
}
// You can then use the data
get_transient( 'my_query_results' );

You can use the query result as a normal query. Isn’t it great ?