Skip to content

Instantly share code, notes, and snippets.

@psorensen
Created March 16, 2021 17:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save psorensen/7abbca7ef824d938df8f36a7b89eb3d1 to your computer and use it in GitHub Desktop.
Save psorensen/7abbca7ef824d938df8f36a7b89eb3d1 to your computer and use it in GitHub Desktop.
Caching a remote request in WordPress
<?php
/**
* Caching a remote response
*
* Related Tutorial: https://pippinsplugins.com/using-wp_remote_get-to-parse-json-from-remote-apis/
*/
// Psuedo Code to demonstrate overall approach
function cached_function() {
if ( has_cached_value() ) {
// return the cached value
} else {
// we have to retrieve the data and then set the cache
}
}
/**
* Annotated Example
*
* @return array
*/
function get_cars_data() {
$endpoint = 'remote-url.json';
$cache_key = 'namespace-data-type';
$data = wp_cache_get( $cache_key ); // try to retrieve the cached value
// if we have a result, return it
if ( $data ) {
return $data;
} else {
// otherwise we need to make the request and then save it to the cache
$request = wp_remote_get( $endpoint ); // todo this probably needs more arguments
if ( is_wp_error( $request ) ) { // bail early if we get an error
return [];
}
$body = wp_remote_retrieve_body( $request ); // get the body of the response
$data = json_decode( $body ); // parse the returned JSON into a PHP array
wp_cache_set( $cache_key, $data ); // finally, now that we have a new value we can set the cache.
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment