PluginProbe
Optimole – Optimize Images | Convert WebP & AVIF | CDN & Lazy Load | Image Optimization / trunk
Optimole – Optimize Images | Convert WebP & AVIF | CDN & Lazy Load | Image Optimization vtrunk
4.2.14 4.2.13 4.2.12 4.2.11 4.2.10 4.2.9 4.2.8 4.2.7 4.2.6 4.2.5 2.5.5 2.5.6 2.5.7 3.0.0 3.0.1 3.1.0 3.1.1 3.1.2 3.1.3 3.10.0 3.11.0 3.11.1 3.11.2 3.11.3 3.12.0 All 135 releases
← All changes | inc/attachment_cache.php +34 -6 3.11.0 → trunk View file →
@@ -3,11 +3,22 @@
3 3 /**
4 4 * Class Optml_Attachment_Cache.
5 5 */
6 6 class Optml_Attachment_Cache {
7 - const CACHE_GROUP = 'optml_attachment_ids';
8 -
7 + const CACHE_GROUP = 'om_att';
9 8 /**
9 + * Local cache map.
10 + *
11 + * @var array
12 + */
13 + private static $cache_map = [];
14 + /**
15 + * Reset the memory cache.
16 + */
17 + public static function reset() {
18 + self::$cache_map = [];
19 + }
20 + /**
10 21 * Get the cached attachment ID.
11 22 *
12 23 * @param string $url the URL of the attachment.
13 24 *
@@ -13,11 +24,21 @@
13 24 *
14 25 * @return bool|mixed
15 26 */
16 27 public static function get_cached_attachment_id( $url ) {
28 +
29 + // We cache also in memory to avoid calling DB every time when not using Object Cache.
17 30 $cache_key = self::get_cache_key( $url );
31 + if ( isset( self::$cache_map[ $cache_key ] ) ) {
32 + return self::$cache_map[ $cache_key ];
33 + }
18 34
19 - return wp_cache_get( $cache_key, self::CACHE_GROUP );
35 + $value = wp_using_ext_object_cache()
36 + ? wp_cache_get( $cache_key, self::CACHE_GROUP )
37 + : get_transient( self::CACHE_GROUP . $cache_key );
38 + self::$cache_map[ $cache_key ] = $value;
39 +
40 + return $value;
20 41 }
21 42
22 43 /**
23 44 * Set the cached attachment ID.
@@ -28,10 +49,17 @@
28 49 * @return void
29 50 */
30 51 public static function set_cached_attachment_id( $url, $id ) {
31 52 $cache_key = self::get_cache_key( $url );
32 -
33 - wp_cache_set( $cache_key, $id, self::CACHE_GROUP, DAY_IN_SECONDS );
53 + // We cache also in memory to avoid calling DB every time when not using Object Cache.
54 + self::$cache_map[ $cache_key ] = $id;
55 + // If the ID is not found we cache for 10 minutes, otherwise for a week.
56 + // We try to reduce the cache time when is not found to
57 + // avoid caching for situation when this might be temporary.
58 + $expiration = $id === 0 ? ( 10 * MINUTE_IN_SECONDS ) : WEEK_IN_SECONDS;
59 + wp_using_ext_object_cache()
60 + ? wp_cache_set( $cache_key, $id, self::CACHE_GROUP, $expiration )
61 + : set_transient( self::CACHE_GROUP . $cache_key, $id, $expiration );
34 62 }
35 63
36 64 /**
37 65 * Generate cache key for URL.
@@ -42,7 +70,7 @@
42 70 */
43 71 private static function get_cache_key( $url ) {
44 72 $url = strtok( $url, '?' );
45 73
46 - return 'attachment_id_' . crc32( $url );
74 + return 'id_' . crc32( $url );
47 75 }
48 76 }