WordPress Transients and APIs

WordPress transients and APIsRecently I have been playing with wp_remote_get to retreive some data from an API. I relized that this was calling the api on every page load. While your site may or may not have a lot of traffic, this is unecessary. Using the built in transient API you can store the data for a given amount of time. Depending on how fresh your data needs to be, will determine how long you should set the expiration. For my use a DAY_IN_SECONDS seemed reasonable. Now one site will only make 1 request per day instead of every page load.

Here is the original line of code


$results = wp_remote_get( $url );

Here is the code after adding the transient


if( false === ( $results = get_transient( 'mh-api-call' ) ) ) {
$results = wp_remote_get( $url );
set_transient( 'mh-api-call', $results, DAY_IN_SECONDS );
}

Since this code will be distributed, I think it will reduce the requests significantly. I will follow up once I have more numbers.