stamped_io_product_reviews_new
was often empty so a new request was being made on every page load, for multiple products. I’ve added caching to the get_request()
function to avoid this:
public static function get_request( $product_id, $product_title, $postfields = array(), $method = 'POST' ) {
$domainName = self::get_site_url();
$public_key = self::get_public_keys();
$baseurl = "https://stamped.io/api/widget?";
$query_args = array(
'productId' => $product_id,
'apiKey' => $public_key,
'storeUrl' => $domainName,
'productName' => $product_title,
);
$transient_name = 'stampedio-'. implode( '-', array_map( 'sanitize_key', $query_args ) );
$transient_value = get_transient( $transient_name );
if( !empty( $transient_value ) ) {
// We're storing the value inside an array key because storing a possibly empty value would not work.
if( isset( $transient_value['data'] ) ) {
return (object) $transient_value['data'];
} else {
return;
}
}
$url = add_query_arg( $query_args, $baseurl );
$request = wp_remote_get(
$url,
array(
'timeout' => 5,
'sslverify' => false,
'headers' => array(
'authorization' => 'Basic {$baseToken}',
'cache-control' => 'no-cache',
'content-type' => 'application/json',
),
)
);
if ( is_wp_error( $request ) ) {
return false; // Bail early
}
$body = wp_remote_retrieve_body( $request );
$data = json_decode( $body );
$transient_data = array( 'expiration_time' => time() + DAY_IN_SECONDS, 'data' => $data );
set_transient( $transient_name, $transient_data, DAY_IN_SECONDS );
if ( ! empty( $data ) ) {
return $data;
}
}