From 54c3fab7d722fc87dd5e80f8a22d44cdc638bb0c Mon Sep 17 00:00:00 2001 From: Filip Ilic Date: Wed, 6 Nov 2024 16:15:04 +0100 Subject: [PATCH] url specific cache key & add (small) cache for failed requests --- classes/class-lessons.php | 32 ++++++++++++++++++++------------ 1 file changed, 20 insertions(+), 12 deletions(-) diff --git a/classes/class-lessons.php b/classes/class-lessons.php index 31613e34d..fa9d807ef 100644 --- a/classes/class-lessons.php +++ b/classes/class-lessons.php @@ -42,37 +42,45 @@ public function get_items() { * @return array */ public function get_remote_api_items() { - $cached = \progress_planner()->get_cache()->get( 'lessons' ); - if ( is_array( $cached ) && ! empty( $cached ) ) { + + /** + * Filter the endpoint url for the lessons. + * + * @param string $endpoint The endpoint url. + */ + $url = apply_filters( + 'progress_planner_lessons_endpoint', + 'https://progressplanner.com/wp-json/progress-planner-saas/v1/free-lessons' + ); + + $cache_key = 'lessons-' . $url; + + $cached = \progress_planner()->get_cache()->get( $cache_key ); + if ( is_array( $cached ) ) { return $cached; } $response = \wp_remote_get( - /** - * Filter the endpoint url for the lessons. - * - * @param string $endpoint The endpoint url. - */ - apply_filters( - 'progress_planner_lessons_endpoint', - 'https://progressplanner.com/wp-json/progress-planner-saas/v1/free-lessons' - ) + $url ); if ( \is_wp_error( $response ) ) { + \progress_planner()->get_cache()->set( $cache_key, [], 5 * MINUTE_IN_SECONDS ); return []; } if ( 200 !== (int) wp_remote_retrieve_response_code( $response ) ) { + \progress_planner()->get_cache()->set( $cache_key, [], 5 * MINUTE_IN_SECONDS ); return []; } $json = json_decode( \wp_remote_retrieve_body( $response ), true ); if ( ! is_array( $json ) ) { + \progress_planner()->get_cache()->set( $cache_key, [], 5 * MINUTE_IN_SECONDS ); return []; } - \progress_planner()->get_cache()->set( 'lessons', $json, WEEK_IN_SECONDS ); + \progress_planner()->get_cache()->set( $cache_key, $json, WEEK_IN_SECONDS ); return $json; }