-
-
Save pagelab/97a2de69fd061975ded7f5a23b36489f to your computer and use it in GitHub Desktop.
wp_remote_get_with_cache – Fetches remote data with dual-layer caching
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Fetches remote data with dual-layer caching. | |
* | |
* Uses wp_remote_get to fetch remote data. The data is cached twice: it's | |
* stored in a transient and an option. The transient is used as the main cache | |
* but if the transient has expired and the remote site doesn't respond, | |
* backup data from the option is returned. | |
* | |
* @param string $url The URL of the remote resource. | |
* @param string $key The name of the option and the transient. | |
* @param array $args Argument array that is passed on to wp_remote_get(). | |
* Default empty array. | |
* @param int $expiry The expiration length of the transient, default | |
* DAY_IN_SECONDS. | |
* @param string $callback A callback function that is applied to the data | |
* before it's saved in the transient and option. Default null. | |
* | |
* @see wp_remote_get() | |
* | |
* @return string The remote data set, JSON encoded. | |
*/ | |
function wp_remote_get_with_cache( $url, $key, $args = array(), $expiry = DAY_IN_SECONDS, $callback = null ) { | |
$data = get_transient( $key ); | |
if ( $data ) { | |
// Data found in cache, return that. | |
return json_decode( $data ); | |
} | |
$response = wp_remote_get( $url, $args ); | |
if ( ! is_array( $response ) ) { | |
// Couldn't get the remote data, set the transient for an hour to avoid | |
// bothering the server and return backup data. | |
$json_encoded_data = json_decode( get_option( $key ) ); | |
set_transient( $key, $json_encoded_data, HOUR_IN_SECONDS ); | |
return $json_encoded_data; | |
} | |
$fetched_data = $response['body']; | |
if ( is_callable( $callback ) ) { | |
$fetched_data = call_user_func( $callback, $fetched_data ); | |
} | |
$json_encoded_data = wp_json_encode( $fetched_data ); | |
set_transient( $key, $json_encoded_data, $expiry ); | |
update_option( $key, $json_encoded_data ); | |
return $fetched_data; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment