Skip to content

Commit

Permalink
Set default for cache key if nothing was set
Browse files Browse the repository at this point in the history
Now we can override default cache key much easier, which allows us to
eg. separate content for different languages when caching it.
  • Loading branch information
ypcs committed Oct 8, 2020
1 parent 07703c4 commit 4539b09
Showing 1 changed file with 54 additions and 0 deletions.
54 changes: 54 additions & 0 deletions seravo-plugin.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
*/
Expand All @@ -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 <https://developer.wordpress.org/reference/functions/apply_filters/>
**/
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
*/
Expand Down

0 comments on commit 4539b09

Please sign in to comment.