From 0133e910ee5adbc3f674325f9e62682c4e9aaef0 Mon Sep 17 00:00:00 2001 From: Jeremy Herve Date: Fri, 2 Feb 2024 17:33:41 +0100 Subject: [PATCH] Stats: add filter to allow customizing the cache duration (#35421) This would allow third-parties to change the default caching duration from 5 minutes to something else, when they need their site to make less queries to WordPress.com in general. --- .../update-stats-pulling-jetpack-filter | 4 ++++ .../packages/stats/src/class-wpcom-stats.php | 24 ++++++++++++++++--- 2 files changed, 25 insertions(+), 3 deletions(-) create mode 100644 projects/packages/stats/changelog/update-stats-pulling-jetpack-filter diff --git a/projects/packages/stats/changelog/update-stats-pulling-jetpack-filter b/projects/packages/stats/changelog/update-stats-pulling-jetpack-filter new file mode 100644 index 0000000000000..ad93f5576381b --- /dev/null +++ b/projects/packages/stats/changelog/update-stats-pulling-jetpack-filter @@ -0,0 +1,4 @@ +Significance: patch +Type: added + +Stats fetching mechanism: add filter allowing one to customize how long we cache results. diff --git a/projects/packages/stats/src/class-wpcom-stats.php b/projects/packages/stats/src/class-wpcom-stats.php index 644bfeea881c9..7b249b9059d6b 100644 --- a/projects/packages/stats/src/class-wpcom-stats.php +++ b/projects/packages/stats/src/class-wpcom-stats.php @@ -398,7 +398,20 @@ protected function fetch_stats( $args = array() ) { // To reduce size in storage: store with time as key, store JSON encoded data. $cached_value = is_wp_error( $wpcom_stats ) ? $wpcom_stats : wp_json_encode( $wpcom_stats ); - $expiration = self::STATS_CACHE_EXPIRATION_IN_MINUTES * MINUTE_IN_SECONDS; + + /** + * Filters the expiration time for the stats cache. + * + * @module stats + * + * @since $$next-version$$ + * + * @param int $expiration The expiration time in minutes. + */ + $expiration = apply_filters( + 'jetpack_fetch_stats_cache_expiration', + self::STATS_CACHE_EXPIRATION_IN_MINUTES * MINUTE_IN_SECONDS + ); set_transient( $transient_name, array( time() => $cached_value ), $expiration ); return $wpcom_stats; @@ -428,8 +441,13 @@ protected function fetch_post_stats( $args, $post_id ) { return $data; } - $time = key( $data ); - $expiration = self::STATS_CACHE_EXPIRATION_IN_MINUTES * MINUTE_IN_SECONDS; + $time = key( $data ); + + /** This filter is already documented in projects/packages/stats/src/class-wpcom-stats.php */ + $expiration = apply_filters( + 'jetpack_fetch_stats_cache_expiration', + self::STATS_CACHE_EXPIRATION_IN_MINUTES * MINUTE_IN_SECONDS + ); if ( ( time() - $time ) < $expiration ) { return array_merge( array( 'cached_at' => $time ), $data[ $time ] );