Search the site:

Copyright 2010 - 2020 @ DevriX - All rights reserved.

What Are Transients APIs?

Website performance often revolves around the idea of caching: storing data in a ready and faster-to-access state, so that it is more quickly reproduced by browsers. The WordPress Transients API is a tool for caching, and a powerful way to improve performance for WordPress websites.

What Is Caching and Why Use It?

Whenever a browser requests a web page, the serving server must do a lot of complex and time-consuming calculations, which leads to delays. After executing a query, thanks to caching technology, the server can remember the end result and upon a second request, provide it to the browser without having to do the same calculations again. Therefore, the ability to cache and reuse earlier resources is crucial to optimizing performance.

Quite simply caching provides the option to store information temporarily in the caching layer.

What Are the Types of Caching?

There are different types of caching and by using a combination of them, you will achieve a higher level of performance.

types of caching

Browser Caching

Before opening the content of a web page, your browser needs a bunch of things like JavaScript files, stylesheets, fonts, and so forth, all of which it downloads in addition to the content of the page.

If a browser caches these files, there will be no need to download them each time you load the website. Loading the site for the first time usually takes a few seconds, but after the browser caches those files, the loading time is reduced significantly.

Server Caching

Server caching means to save the HTML file for a particular page and to use if for each subsequent request. This is the so-called full page cache.

There is another type of server cache – object cache, which, unlike full page cache, caches only certain bits (pieces) of information.

Page Caching

Considered the most effective cache. Its name is self-explanatory to the way it works. When user ‘A‘ visits a page, the website will build it and return it content to the user’s browser. With Page Cache running, this page content is saved so that when user ‘B‘ visits the same page, the page cache reproduces the previously sent content.

The greatest advantage of Page Cache is that the cached page returns almost at the moment of access. As a result, millions of requests are processed and pages reproduced even on the weakest server with the poorest memory speed and little CPU usage.

But this type of cache also has its drawbacks: for example, the inability to cache pages for an authorized user, or for a user whose page content depends on current user variables.

Database Caching

Database caching is a process included in the design of computer applications that generate web pages on-demand (dynamically) by accessing backend databases. A database cache enhances your primary database by removing unnecessary pressure on it, typically in the form of frequently accessed read data. The cache itself can operate in a number of areas including your database, application or as a standalone layer.

When these applications are deployed on multi-tier environments that involve browser-based clients, web application servers and backend databases, middle-tier database caching is used to achieve high scalability and performance.

Object Caching

Object caching in WordPress (object cache)involves storing database queries. It is a built-in system mechanism that allows you to save data (objects) of any type and retrieve it when necessary. This cache is used to store the results of complex operations.

When enabled on your WordPress site, it helps speed up PHP execution times, deliver content to the site visitors faster, and reduce the load on the database.

CDN (Content delivery networks)

It is a geographically distributed network infrastructure that provides fast delivery of content to users of web services and sites. The servers included in the CDN are geographically located in such a way as to make the response time for users of the site/service minimal.

What Is a Transients API in WordPress?

Transients API is the way to store a block of information (a string of code, HTML content, WP_Query Objects, JSON) in the website’s database as opposed to browser caching. Transients API is very similar to the Options API, but the main difference is that Transients API has an expiration time or better said lifespan.

The three main operations for transients are setting values, getting values, and deleting values:

1. Set a Transient –

set_transient( $key, $value, $expires );

To set a transient you can use set_transient() function which has three components:

  • Key – Short unique name of the transient. Must be 172 characters or fewer in length.
  • Value – Any type of PHP variable that contains the information which will be stored in the database.
  • Expiration Time (lifespan) – The amount of time for which the information will be stored.

So for example if we want to save our listing posts query for one day:

set_transient( 'unique_listing_posts_query_results_name', 
$listing_posts_query_results, DAY_IN_SECONDS );

As you can see we have used one (DAY_IN_SECONDS) of the several time constants introduced in WordPress 3.5 to easily express time. Here is a complete list of all-time constants:

MINUTE_IN_SECONDS  = 60 (seconds)
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

 

2. Get a Transient –

get_transient( $key );

To get a saved transient we can use

get_transient( $transient_name );

In our case we could fetch our posts listing query results with:

get_transient( 'unique_listing_posts_query_results_name' );

We will see more on that later in our example section.

3. Delete a Transient –

delete_transient( $key );

As we explained in the previous subsections we can use Transients API to get and store remote or local (content or query from our database) responses to our database.

However, here comes the question of how we delete old stored content (transient). There are two ways to clear (delete) transients:

Automatic Deletion

The cool thing about transients is that they expire automatically if we set expiration time (lifespan). If you attempt to retrieve a transient from your database after it has expired, WordPress will automatically delete it, preventing any clutter. The transient will be recreated once someone opens the website. This way we are ensuring that we have fresh content from the remote or local API.

Manual Deletion

Sometimes we will need to force the transient to die early by manually deleting it. This is useful when given activity (adding new menu item, saving or updating a post, adding or updating a category etc.) will make the cached data inherently stale and in need of updating:

The function which we must use is

delete_transient( $transient_name )

and in our case it should be:

delete_transient( 'unique_listing_posts_query_results_name' );

Note: It’s important NOT to use transients for storing valuable data that cannot be re-created!

Why Should We Use Transients APIs?

We can use the Transients API whenever we have a computationally-intensive value that doesn’t change very often and that you’d like to cache. In WordPress, this is usually going to be the resulting object from a database query, but it could really be anything you’d store in a variable, whether a scalar value, an array or an object.

So all in all transients are great when you’re doing complex queries in your themes and plugins.

Benefits of Caching Remote or Local Responses

Remote API responses

The Remote APIs always make several calls or requests to remote servers and there is some extra latency. This takes time and causes delays. Also, some remote APIs can have rate-limits, meaning you can reach the maximum requests limit within a given time period.

And as you already know, we can take advantage of Transients API to cache the response (result) from the remote server and to store it in our database. Now we can use the

get_transient();

method and show the stored (cached) result/content wherever needed without making other remote calls or requests.

All this will:

  • Reduce the remote HTTPS calls and requests
  • Reduce the CPU server usage
  • Improve the website page load time

Local API responses

– basically the HTML or query results from the database. You can use Transients API not only for caching remote responses but also for storing HTML content or query results in the local database. It’s very useful if you want to show a repeatable HTML section on your website (widgets, sliders, menus, etc.) or just to prevent complex or slow database queries to be triggered every time when someone visits your website.

Where and When to Use Transients?

  • Complex and custom database queries
  • WordPress navigation menus
  • Sidebar widgets that display info like; tweets, a list of recent site visitors or a list of posts from a certain category
  • Caching tag clouds
  • Caching external HTTP requests

Usage and Examples

After so many explanations it’s time for real examples.

Basic Usage

function get_my_data(){

$data = get_transient( 'my_transient_name' );

if ( false === $data ){ // Transient was expired/hasn’t been set

$data = fetch_my_data(); // Pull data from original source

set_transient( 'my_transient_name', $data, HOUR_IN_SECONDS );

}

return $data;

}

fetch_my_data() function can store WP_Query object, json data, html content, etc.

Basic Example

As we’ve already explained this type of caching is good for saving the result of long operations, and the simplest example is accessing external APIs, such as Facebook.

Imagine we have the following function, which accesses the Facebook API, requests an object (more precisely, a page) your-website.url and returns the number of likes of the page:

function get_facebook_likes() {

    $result = wp_remote_get( 'https://graph.facebook.com/your-website.url' );

    $result = json_decode( wp_remote_retrieve_body( $result ) );

    return $result->likes;

}

echo "Facebook likes: " . get_facebook_likes();

The execution time of this function depends on many factors, including the location of your server relative to Facebook servers, the status, and speed of the network, etc. On average, a function can take 1-3 seconds.

This means that when using this function on the site, the loading time of each page will increase by 1-3 seconds. Moreover, if we call this function more than 500 times in 500 seconds, Facebook will start to generate an error instead of a result.

To speed up this feature, we can use WordPress Transients API and save the result for 1 hour:

function get_facebook_likes() {
if ( false === ( $likes = get_transient( 'fb_likes' ) ) ) {
$result = wp_remote_get( 'https://graph.facebook.com/your-website.url' );
$result = json_decode( wp_remote_retrieve_body( $result ) );
$likes = $result->likes;

// Set transient for an hour in seconds
set_transient( 'fb_likes', $likes, 1 * HOUR_IN_SECONDS );
}

return $likes;
}

Thus, when this function is called for the first time, after receiving a request from Facebook, WordPress will write the result to the database and in the future will return this result from the database for an hour without making repeated requests to the Facebook server. And after an hour, the function will again turn to Facebook for data.

With this approach, only one call to this function per hour will increase the request time by 1-3 seconds, and subsequent calls will be issued instantly.

More Complex Example

Imagine that we have a website with about 100 categories and about 50 000 posts, and in the website’s single post design we have a widget that shows the N related posts from the category in which the current post is. As expected, this complex query will take some time to take the result from the database and show it on the website.

Now imagine that you have 10 000 users who access the website at the same time. This means that we will have 10 000+ database requests that have to do the query (this is a complex query as it would search through wp_terms, wp_term_relationships, wp_term_taxonomy, wp_posts tables, so they are more than 10 000 queries), to get the result for the N posts from the related category and to show them on the frontend. This, in turn, would overload the database and delay the overall loading time of the website, and in some cases even crash it due to overloading the database.

And here comes the question of how can we optimize and reduce the number of database queries and requests. Why have so many queries every time when we can take advantage of the Transients API and just cache the query object or cache the entire HTML output? This way we’ll reduce and optimize the number of database queries, which will lead to better website performance and better user experience.

In our case the queries will search in wp_terms, wp_term_relationships, wp_term_taxonomy, wp_posts tables to get all expected results.

Here is a complete example of how we can accomplish this:

function show_posts_from_category() {
$args = array(
'cat' => 555, // Random category ID
'posts_per_page' => 8, // Random number of related posts to display
'No_found_rows' => true,
);

$hash = md5( $args['cat'] ); // MD5 hash of the category ID
$transient_key = 'category-' . $hash; // Transient Key

if ( false === ( $posts_from_category_html = get_transient( $transient_key ) ) ) : // Transient was expired/hasn’t been set

$the_query = new WP_Query( $args ); // Get the query

ob_start(); // Turn output buffering on

while ( $the_query->have_posts() ) : $the_query->the_post();
?>
<div class="item">
<div class="bigthumb">
<a href="<?php the_permalink();?>" rel="bookmark" title="<?php the_title(); ?>"> <?php if ( has_post_thumbnail() ) the_post_thumbnail('big-thumb'); ?></a>
</div>
<h3><a href="<?php the_permalink();?>" rel="bookmark" title="<?php the_title(); ?>"><?php the_title(); ?></a></h3>
<?php the_excerpt(); ?>
</div>
<?php
endwhile;

$post_from_category_html = ob_get_contents(); // Gets the contents of the output buffer without clearing it
ob_end_clean(); // Turns off this output buffering

set_transient( $transient_key, $posts_from_category_html, $transient_expire = 15 * MINUTE_IN_SECONDS ); // Setting the transient with 15 mins expiration time

wp_reset_postdata();
endif;

return $post_from_category_html;
}

Final Thoughts

Caching is a great way to speed things up, but you have to know exactly what you’re caching, where you can do it, when and how, otherwise you risk facing unexpected consequences.

If you’re uncertain whether something is working as intended, always turn to profiling — look at each query against the database, look at all PHP function calls, the timing and memory usage.

Transients API is a great way to optimize the loading time of your WordPress website and to deliver an exceptional user experience. Using transients in your plugins and themes is simple and only adds a few extra lines of code. When used in the right situations – like long database queries or complex processed data – it can save seconds off the load times on your site.

Leave a Reply

Your email address will not be published. Required fields are marked *