diff options
Diffstat (limited to 'plugins/jetpack/modules/related-posts/jetpack-related-posts.php')
-rw-r--r-- | plugins/jetpack/modules/related-posts/jetpack-related-posts.php | 61 |
1 files changed, 41 insertions, 20 deletions
diff --git a/plugins/jetpack/modules/related-posts/jetpack-related-posts.php b/plugins/jetpack/modules/related-posts/jetpack-related-posts.php index f8eaff22..5748e6a2 100644 --- a/plugins/jetpack/modules/related-posts/jetpack-related-posts.php +++ b/plugins/jetpack/modules/related-posts/jetpack-related-posts.php @@ -1014,17 +1014,27 @@ EOT; if ( !empty( $filters ) ) $body['filter'] = array( 'and' => $filters ); - // Load all cached values - $cache = get_post_meta( $post_id, $cache_meta_key, true ); - if ( empty( $cache ) ) - $cache = array(); - // Build cache key $cache_key = md5( serialize( $body ) ); - // Cache is valid! Return cached value. - if ( isset( $cache[ $cache_key ] ) && is_array( $cache[ $cache_key ] ) && $cache[ $cache_key ][ 'expires' ] > $now_ts ) { - return $cache[ $cache_key ][ 'payload' ]; + // Load all cached values + if ( wp_using_ext_object_cache() ) { + $transient_name = "{$cache_meta_key}_{$cache_key}_{$post_id}"; + $cache = get_transient( $transient_name ); + if ( false !== $cache ) { + return $cache; + } + } else { + $cache = get_post_meta( $post_id, $cache_meta_key, true ); + + if ( empty( $cache ) ) + $cache = array(); + + + // Cache is valid! Return cached value. + if ( isset( $cache[ $cache_key ] ) && is_array( $cache[ $cache_key ] ) && $cache[ $cache_key ][ 'expires' ] > $now_ts ) { + return $cache[ $cache_key ][ 'payload' ]; + } } $response = wp_remote_post( @@ -1055,25 +1065,36 @@ EOT; } } - // Copy all valid cache values - $new_cache = array(); - foreach ( $cache as $k => $v ) { - if ( is_array( $v ) && $v[ 'expires' ] > $now_ts ) { - $new_cache[ $k ] = $v; - } + // An empty array might indicate no related posts or that posts + // are not yet synced to WordPress.com, so we cache for only 1 + // minute in this case + if ( empty( $related_posts ) ) { + $cache_ttl = 60; + } else { + $cache_ttl = 12 * HOUR_IN_SECONDS; } - // Set new cache value if valid - if ( ! empty( $related_posts ) ) { + // Update cache + if ( wp_using_ext_object_cache() ) { + set_transient( $transient_name, $related_posts, $cache_ttl ); + } else { + // Copy all valid cache values + $new_cache = array(); + foreach ( $cache as $k => $v ) { + if ( is_array( $v ) && $v[ 'expires' ] > $now_ts ) { + $new_cache[ $k ] = $v; + } + } + + // Set new cache value + $cache_expires = $cache_ttl + $now_ts; $new_cache[ $cache_key ] = array( - 'expires' => 12 * HOUR_IN_SECONDS + $now_ts, + 'expires' => $cache_expires, 'payload' => $related_posts, ); + update_post_meta( $post_id, $cache_meta_key, $new_cache ); } - // Update cache - update_post_meta( $post_id, $cache_meta_key, $new_cache ); - return $related_posts; } |