KatPadi's Point

WP Transients to Cache API Response

Being the amateur person that I am, I did not employ caching in my API calls just recently. I ignored its importance because I didn’t expect we would get that many hits. (Hey, the site wasn’t serious initially!) Either way, it’s still unacceptable.

Come on Kat, you should know better than this!!!

API response data must be served to the users from the cache. So instead of requesting (GET) data every time someone loads the website, store it in a local cache then serve the cached version to the users.

So I was using WP and I just recently learned about their thing called Transients API.

Transients API makes it easy to store data into the WP database temporarily, given a timeframe.

There are only two important things to be remembered here:

  1. get_transient
  2. set_transient

Anyway, I was getting game results for a certain NBA team. I only need the data updated once daily because stats and standings only change once per day.

What I did was like this:

// Check if there exists a cached data or if it's still not expired
$game_result = get_transient( "game_result" );

if( false === $game_result ) {
    // Hit whatever URL you need to get data from
    $response = wp_remote_get( "URL_TO_HIT", $some_args);
    // Parse the response and save to the data that you want to show
    $game_result =  json_decode($response['body']);
    //  Save the transient aka data --- this is the important part !!! 
    // Also, specify the expiry --- in my example it's a 12-hour cache
    set_transient('game_result', $game_result, 60*60*12); 
// Simply output
echo $game_result;


Leave a Reply

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