From 4539b0952d29768047c24a8f91ef247847d031ee Mon Sep 17 00:00:00 2001 From: Ville Korhonen Date: Wed, 7 Oct 2020 15:04:54 +0300 Subject: [PATCH] Set default for cache key if nothing was set Now we can override default cache key much easier, which allows us to eg. separate content for different languages when caching it. --- seravo-plugin.php | 54 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) diff --git a/seravo-plugin.php b/seravo-plugin.php index 99dfd634..b40e2831 100644 --- a/seravo-plugin.php +++ b/seravo-plugin.php @@ -66,6 +66,11 @@ public function __construct() { } self::$_single = $this; // Singleton set. + /* + * On site init, ensure we have good default for cache key + */ + add_action('init', array( $this, 'cache_key' ), 1); + /* * Load translations */ @@ -84,6 +89,55 @@ public function __construct() { add_action('init', array( $this, 'load_all_modules' ), 20); } + /** + * Configure WP_CACHE_KEY_SALT + * + * This makes sure that we always try our best to cache contents as user + * expects us - no content in wrong languages etc. Value is consumed by the + * object-cache.php that's distributed with Seravo WordPress template + * project. + * + * You can modify the response by hooking to `seravo_cache_key` filter. + * Filter accepts $key as parameter, which is an array of key => value + * pairs which will then be used to construct the actual key string. + * + * @see + **/ + public function cache_key() { + // If cache key salt is already defined, stop here + if ( defined('WP_CACHE_KEY_SALT') ) {return;} + + $key = array(); + + // If this is a multisite, ensure site_id is part of the cache key to + // prevent mixing up content from different sites. + if ( is_multisite() ) { + $current_site = get_current_site(); + $id = $current_site->id; + $key[] = array( 'site_id' => "${id}" ); + } + + // If WPML language code has been defined, append it to the cache + // key to prevent content for different languages from being mixed + // up. + if ( defined('ICL_LANGUAGE_CODE') ) { + $key[] = array( 'wpml' => ICL_LANGUAGE_CODE ); + } + + // Apply filters, you can hook to this filter if you want to add your + // own config, or modify the default values. + $key = apply_filters('seravo_cache_key', $key); + + if ( ! defined('WP_CACHE_KEY_SALT') ) { + // Convert key to base64-encoded HTTP query-formatted string, + // ensures that independend of the array contents key is somewhat + // sane. + $ckey = 's_' . base64_encode(http_build_query($key, '', ';')); + define('WP_CACHE_KEY_SALT', $ckey); + } + } + + /** * Pass report file on to admin users */