function wnet_get_transient_remote_json($transientname, $url, $interval=1800) {
// those are the same arguments as 'set_transient()'
$stalecachename = 'stalecache_' . $transientname;
// we generate a consistent name for the backup data
if ( false === ( $json = get_transient($transientname) ) ) {
$response = wp_remote_get($url);
// get the remote data as before, but this time...
if (is_wp_error($response) || ! isset($response['body']) || 200 != $response['response']['code']) {
// check to see all of the ways that the data request could return an error.
$json = get_option($stalecachename);
// one of our checks failed, so we get the stale cache data from WP Options and store in the $json variable.
} else {
$json = $response['body'];
// no errors! we store the remote data in the $json variable.
if (! get_option($stalecachename)) {
add_option($stalecachename, $json, '', 'no');
// Store the data in the $json variable in the options table as a backup.
// We _could_ have just used update_option(), but by using add_option() with 'no' in the third arg
// we keep the option from being 'autoloaded' into memory and reducing memory usage.
} else {
update_option($stalecachename, $json);
// update_option() preserves the 'autoload' setting of a previously created option.
}
}
set_transient($transientname, $json, $interval );
// Regardless of whether we got the data from the remote site or our local backup, we store that data in the transient.
// We won't try to regenerate that data until the transient expires.
}
return $json;
// on general principle return the data we are storing in case we'd like to do something with it.
}
}<