Optimize Your WordPress Site with the Transients API: A Detailed Guide
If you’re a WordPress savvy developer, you’ve definitely heard the word “Transients” at least once. Transients provide you a super useful way to speed up your WordPress site by storing volatile data in the database. Despite of the fact that Transients API is supported in WordPress since version 2.8, many users are still not aware of its existence, functionality and uses.
In this tutorial, I’ll take a close look at the Transients API: one of the lesser-known and most overlooked APIs in WordPress. After going through this blog post, you would have learned:
- What’s The Transients API?
- Is It Really Similar to the Options API?
- When Should You Use Transients API?
- How Can You Use It?
- How Do Transients Function (via Practical Examples)?
So, let’s begin!
What’s The Transients API?
Simply put, the Transients API is a great way to store cached data in the WordPress database for a fixed amount of time. To store cached information, all you need to do is give it a custom name and set an expiration time after which it’ll be deleted. In a standard WordPress installation, the Transients API makes use of wp_options table to store cached data in the database.
Taking a key-value approach, the Transients API lets you store cached information against a key value that has an expiration time, after which the stored data gets removed from the database. Whatever data you’ve stored in the database can be retrieved anytime only before your specified time without hitting the database.
WordPress by default stores transient values in the database, but caching plug-ins further speed up Transients by storing them in fast memory, like Memcached, rather than in the database. That means, Transients are perfect for storing any data that can expire at any time and therefore you should never use them to store any critical data.
Is It Really Similar to the Options API?
Yeah! Transients API is quite identical to the Options API, with the only difference that it has an expiration time. Where Options save the cache data permanently in the database, on the other side, Transients can be saved for a limited amount of time. Before you store a transient, you have to specify the maximum number of seconds you want to keep the cached information in database. When the expiry time is reached, the transient would automatically be removed from the database. On the contrary, Options remain in the database until you manually remove them.
Unlike all other WordPress APIs, which use both non-persistent (WordPress Object Cache) persistent cache to synchronize the data to ensure data persistency, Transients API only uses the Object Cache if you’ve installed a persistent cache plug-in on your site. Implementing Object Cache, cached data is stored persistently across page loads instead of in the database. However if persistent caching is not configured, Transients API takes advantage of Options API to store the data in wp_options table. Keep in mind, a Transient contains two Options: one is key/value pair data and another is key/value pair expiry time.
When Should You Use Transients API?
It’s absolutely true that you can use Transients API to cache almost anything but to be on the safe side, it must be used to cache data that will expire after a certain amount of time. Remember, Transients can expire even before your specified expiry time, so never use them to cache crucial data which you don’t want to lose at any cost. As a general rule, you can use transients when:
- You want to fetch specific information from a third party site or API. For example, when connecting to an external website for getting the latest RSS feed entries or to the Facebook API to request your latest statuses.
- You run complex, resource heavy and slow database queries, like querying comments, latest posts, navigation menus or other similar things.
- You use complex and resource heavy functions/ methods that generate a good load of HTML code, which you can store in a Transient.
- You want to cache queries that are updated rarely or not shown immediately.
- You find fit to use it!
In a nutshell, use a Transient only if your data does need to expire. If not, it would be better for you to use an Option. One more thing, never forget to set an expiration time while saving a Transient, otherwise your data would not be stored the way you want.
How Can You Use It?
Getting started with Transients is as easy as one, two and three. You just need to be familiar with these three basic functions:
- set_transient(): Used to save a Transient.
- get_transient(): Used to retrieve a saved Transient.
- delete_transient(): Used to manually delete a Transient to force it to die early.
Each of the above functions has two versions: site-specific and network-wide. The site-specific version makes a Transient available to the specified site in a Multisite Network, while the network-wide version is used to make it available across the entire Multisite installation.
If you’ve ever worked with the Options API, you’ll find these functions working in the same way as add_option(), get_option() and delete_option() functions.
Let’s go through these three basic functions one by one.
Setting a Transient:
To save a transient, you need to use set_transient() function which requires three parameters to be passed:
- $transient (required): The name of the Transient. It must be a string which shouldn’t be more than 40 characters in length.
- $value (required): The data to be stored in the transient. It must also be a string. And if you pass complex data like an object or array, the API will convert it to a string by handling serialization.
- $expiration (optional): The number of seconds you want to store the data before refreshing. It must be an integer value. Remember, Transients may expire before your specified time for any reason, like database upgrades.
Below is the syntax of the method:
set_transient( $transient, $value, $expiration );
Easy, right? Here is a simple example of implementing set_transient() function:
set_transient(‘twitter username’, ‘yourajit’, 43200);
In above example, I’m storing my twitter username “yourajit” for 12 hours. After 12 hours, the value of this transient can’t be retrieved.
For the $expiration parameter, you can either directly input an integer value or easily express time using several constants that were introduced in WordPress 3.5:
- 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
- YEAR_IN_SECONDS = 365 * DAY_IN_SECONDS
Now, the code sample I’ve given above can be simplified to:
set_transient(‘twitter username’, ‘yourajit’, 12 * HOUR_IN_SECONDS);
Keep in mind, if the transient is created successfully, the set_transient() function will return true otherwise it’ll return false.
Now, if I wish to make this transient available for all the sites in my Multisite network, then I would have to use set_site_transient() function as follows:
set_site_transient(‘twitter username’, ‘yourajit’, 12 *HOUR_IN_SECONDS);
Retrieve a Transient:
To get a stored transient, you can use get_transient() function which accepts only the name of the transient.
get_transient( $transient );
In my case, I can fetch my twitter username with:
get_transient( ‘twitter username’ );
If the transient is expired or not found, then get_transient() function will return false otherwise it’ll return the value of the transient. Therefore, you should not use transients to hold plain Boolean values (true and false). However, you can use their integer form (1 and 0) if you wish to store them in a transient.
If you’ve used set_site_transient() to save a transient, then use get_site_transient() to fetch it.
Deleting a Transient:
In some cases, you may want to manually remove a transient before its expiration time. You can easily delete a transient using delete_transient() function that takes the same parameter as get_transient() function, i.e. transient name.
delete_transient( $transient );
In my case, this would be:
delete_transient( ‘twitter username’ );
If the transient was deleted successfully, the delete_transient() function will return true. Otherwise, if the transient couldn’t be deleted for any reason, it’ll return false.
If you’ve saved a transient using set_site_transient(), then you would need to use delete_site_transient() to delete it.
Practical Examples on Using Transients API
Let’s dive into the real power of Transients through some hands-on examples.
Caching Posts of a Particular Category:
In this example, I’m caching the posts of a category, named “javascript”, for 12 hours. To retrieve the posts of this category, I’ve used transients with WP_Query class.
<?php
if ( false === ($posts = get_transient(“mysite_javascript_posts”))) {
$posts = new WP_Query(“category_name=javascript”);
set_transient(“mysite_javascript_posts”, $posts, 12 * HOUR_IN_SECONDS);
}
?>
<?php if($posts->have_posts()): ?>
<?php while($posts->have_posts()) : $posts->the_post(); ?>
<?php endwhile; ?>
<?php else: ?>
<?php endif; ?>
<?php wp_reset_postdata(); ?>
Caching the Navigation Menu:
This example shows you how to use the Transients API to cache the navigation menu for one day. By integrating the following PHP function – which replaces the core function wp_nav_menu() – into your theme, you can speed up your WordPress site a lot.
<?php
function theme_nav_menu( $theme_location, $class = ‘menu’ )
{
$menu = get_transient( ‘nav-‘ . $theme_location );
if( $menu === false )
{
if( has_nav_menu( $theme_location ) )
{
$menu = wp_nav_menu( array(
‘theme_location’ => $theme_location,
‘menu_class’ => $class,
‘echo’ => 0,
) );
set_transient( ‘nav-‘ . $theme_location, $menu, DAY_IN_SECONDS );
}
}
echo $menu;
}
?>
Caching the Tag Cloud:
With Transients API, you can even cache your tag cloud. The following code shows how you can cache the tag cloud for the duration of one week.
$tag_cloud = get_transient( ‘tag_cloud’ );
if ( false === $tag_cloud || ” === $tag_cloud ){
$args = array (‘echo’ => false);
$tag_cloud = wp_tag_cloud( $args );
set_transient( ‘tag_cloud’, $tag_cloud, WEEK_IN_SECONDS );
}
echo $tag_cloud;
Caching Any Custom Query:
Moreover, you can take advantage of the Transients API to cache custom queries. For the sake of an example, suppose you have a sidebar widget that performs a database query for 10 latest posts. To reduce the database load, you can use Transients to cache the results for a fixed amount of time, like one hour, as follows:
<?php
if (false === ( $sidebar_widget_query_results = get_transient(‘sidebar_widget_query_results’) ) ) {
$sidebar_widget_query_results = new WP_Query(‘order=random&post_count=10’);
set_transient(‘sidebar_widget_query_results’, $sidebar_widget_query_results, HOUR_IN_SECONDS);
}
?>
Here is my author Bio:-
Ajeet is a senior web developer at WordPressIntegration – PSD to WordPress Coders – where he writes custom JavaScript code for WordPress themes. In his spare time, he writes about different topics related to JavaScript, WordPress, and HTML5 to share his work experience with others. You can follow wordpressintegration on Facebook
You must be logged in to post a comment.