Sometimes in WordPress or really on any other site you have to show something on your site that uses the results from another server like an API call or data about something someone else owns.
If you want to increase efficiency and not have to hit and wait for a response from the foreign resource every time a user does a search and the search itself is common, WordPress has a built in method for this called “transients”. If you have a bit of data that you have to call more than once and takes a lot of resources to get/calculate, you may want to store it in a transient so the data is stored in an easy-to-access place.
A transient is a single piece of data that is stored in the options
table like an option
, but they are different in that they expire. If I am storing API results, I would not want to store results in 2012 and then have a user in 2022 use the same data. There is a good chance that the API has changed and that data is no longer correct. So a transient is to store a bit of calculated, usually external data, for easy retrieval within a reasonable amount of time. If the transient has expired when the second user does the same search then the API results are gathered again and the transient is remade with the new data and with the expiration timer starting over. Let’s take a look at how transient code looks:
// if the transient does not exist or exists but expired
if ( get_transient('search_results_' . $search_term) == false ) {
// get the search data for the term from the API
$contents = wp_remote_get( 'https://APIURL/' . $search_term);
// get only the body of the API response
$body = wp_remote_retrieve_body( $contents );
// decode the JSON array response for use into a PHP array
$api_results = json_decode($body, true)['entry'];
// delete expired transient if it exists
delete_transient( 'search_results_' . $search_term );
// since there was no valid transient for this search, store the results
set_transient( 'search_results_' . $search_term, $api_results, 3600 );
// the transient does exist so get the value from the database where it was stored last time
} else {
// since this search was done before and stored, get the stored results
$api_results = get_transient( 'search_results_' . $search_term );
}