Skip to content

Commit

Permalink
Stats: add filter to allow customizing the cache duration (#35421)
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
jeherve authored Feb 2, 2024
1 parent 202e306 commit b493b7d
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 3 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Significance: patch
Type: added

Stats fetching mechanism: add filter allowing one to customize how long we cache results.
24 changes: 21 additions & 3 deletions projects/packages/stats/src/class-wpcom-stats.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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 ] );
Expand Down

0 comments on commit b493b7d

Please sign in to comment.