From dd27bf278b83d34c70a24932563cd1330c6b36f6 Mon Sep 17 00:00:00 2001 From: haszari Date: Thu, 21 Feb 2019 10:20:58 +1300 Subject: [PATCH] =?UTF-8?q?cache=20empty=20suggestions=20if=20API=20fails,?= =?UTF-8?q?=20to=20reduce=20congestion/thrashing=20+=20+=20don't=20use=20w?= =?UTF-8?q?p=5Fremote=5Fsafe=5Fget=20=E2=80=93=20overkill=20+=20use=20wp?= =?UTF-8?q?=5Fsend=5Fjson=5Fsuccess=20to=20streamline/simplify=20API=20dat?= =?UTF-8?q?a=20ajax=20handler?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../class-wc-marketplace-suggestions-api.php | 26 ++++++++----------- 1 file changed, 11 insertions(+), 15 deletions(-) diff --git a/includes/marketplace-suggestions/class-wc-marketplace-suggestions-api.php b/includes/marketplace-suggestions/class-wc-marketplace-suggestions-api.php index 640fc8a2b98..73c4c9b80e0 100644 --- a/includes/marketplace-suggestions/class-wc-marketplace-suggestions-api.php +++ b/includes/marketplace-suggestions/class-wc-marketplace-suggestions-api.php @@ -16,30 +16,29 @@ defined( 'ABSPATH' ) || exit; * @return array of json API data */ function wc_marketplace_suggestions_get_api_data() { - $suggestion_data_url = 'https://d3t0oesq8995hv.cloudfront.net/add-ons/marketplace-suggestions.json'; - $suggestion_data = get_transient( 'wc_marketplace_suggestions' ); - if ( false !== $suggestion_data ) { return $suggestion_data; } - $raw_suggestions = wp_safe_remote_get( + $suggestion_data_url = 'https://d3t0oesq8995hv.cloudfront.net/add-ons/marketplace-suggestions.json'; + $raw_suggestions = wp_remote_get( $suggestion_data_url, array( 'user-agent' => 'WooCommerce Marketplace Suggestions' ) ); - if ( is_wp_error( $raw_suggestions ) ) { - return array(); - } // Parse the data to check for any errors. // If it's valid, store structure in transient. - $suggestions = json_decode( wp_remote_retrieve_body( $raw_suggestions ) ); - if ( $suggestions && is_array( $suggestions ) ) { - set_transient( 'wc_marketplace_suggestions', $suggestions, WEEK_IN_SECONDS ); - return $suggestions; + if ( ! is_wp_error( $raw_suggestions ) ) { + $suggestions = json_decode( wp_remote_retrieve_body( $raw_suggestions ) ); + if ( $suggestions && is_array( $suggestions ) ) { + set_transient( 'wc_marketplace_suggestions', $suggestions, WEEK_IN_SECONDS ); + return $suggestions; + } } + // Cache empty suggestions data to reduce requests if there are any issues with API. + set_transient( 'wc_marketplace_suggestions', '[]', DAY_IN_SECONDS ); return array(); } @@ -48,10 +47,7 @@ function wc_marketplace_suggestions_get_api_data() { */ function wc_marketplace_suggestions_ajax_handler() { $suggestion_data = wc_marketplace_suggestions_get_api_data(); - - echo wp_json_encode( $suggestion_data ); - - wp_die(); + wp_send_json_success( $suggestion_data ); }