Skip to content

Instantly share code, notes, and snippets.

@rahulsprajapati
Created November 25, 2021 17:14
Show Gist options
  • Save rahulsprajapati/7126ec2d070f17893076a0d1835c16b7 to your computer and use it in GitHub Desktop.
Save rahulsprajapati/7126ec2d070f17893076a0d1835c16b7 to your computer and use it in GitHub Desktop.
Cache sucess API responses in WordPress.
<?php
/**
* Cache http response to store response data in cache once received success response.
* This helps avoiding duplicate http requests.
* Also helpful in cases where we may have limited API requests rate. (i.e 25 requests per day)
*/
namespace WP_Local_Helper;
// Domain list which needs uncached response each time.
const EXCLUDE_CACHE_DOMAIN_LIST = [
'example.org',
];
const CACHE_GROUP = 'local-helper';
/**
* Maybe return respose from cache.
*
* @param false|array $response A preemptive return value of an HTTP request.
* @param array $parsed_args HTTP request arguments.
* @param string $url The request URL.
*
* @return false|array
*/
function maybe_return_cache_response( $response, $parsed_args, $url ) {
$request_domain = wp_parse_url( $url, PHP_URL_HOST );
$cache_key = wp_hash( wp_json_encode( $parsed_args ) . $url );
$cache_response = wp_cache_get( $cache_key, CACHE_GROUP );
if ( in_array( $request_domain, EXCLUDE_CACHE_DOMAIN_LIST ) || false === $cache_response ) {
return $response;
}
// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
error_log( 'Return cache response. URL: ' . $url );
return $cache_response;
}
add_filter('pre_http_request', __NAMESPACE__ . '\\maybe_return_cache_response', 10, 3 );
/**
* Filters the HTTP API response immediately before the response is returned.
*
* @param array $response HTTP response.
* @param array $parsed_args HTTP request arguments.
* @param string $url The request URL.
*
* @return false|array
*/
function maybe_cache_response( $response, $parsed_args, $url ) {
$request_domain = wp_parse_url( $url, PHP_URL_HOST );
if (
! in_array( $request_domain, EXCLUDE_CACHE_DOMAIN_LIST )
&& ! empty( $response['response']['code'] )
&& $response['response']['code'] === 200
) {
$cache_key = wp_hash( wp_json_encode( $parsed_args ) . $url );
wp_cache_set( $cache_key, $response, CACHE_GROUP );
// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
error_log( 'Set cache response. URL: ' . $url );
}
return $response;
}
add_filter('http_response', __NAMESPACE__ . '\\maybe_cache_response', 10, 3 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment