Skip to content

Instantly share code, notes, and snippets.

@edlefebvre
Created October 8, 2019 13:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save edlefebvre/390ba10773a8ac2b2807f9f268715e56 to your computer and use it in GitHub Desktop.
Save edlefebvre/390ba10773a8ac2b2807f9f268715e56 to your computer and use it in GitHub Desktop.
Fragment caching function
<?php
/**
* Fragment caching function
* see: https://css-tricks.com/wordpress-fragment-caching-revisited/
*
* Usage:
* <?php fragment_cache('frc_footer', DAY_IN_SECONDS, function() { ?>
* code to cache (loops etc)
* <?php }); // end fragment_cache ?>
*/
// Exit if accessed directly
if ( !defined('ABSPATH') ) exit;
// Random prefix that will define / invalidate transients
function frc_prefix() {
return get_option('frc_random_prefix');
}
add_action('fragment_cache_prefix', 'frc_prefix');
// Clear cache when saving a post
function clear_cache() {
$random = rand(0,999);
update_option('frc_random_prefix',$random);
}
add_action('save_post','clear_cache');
// Fragment cache
function fragment_cache($key, $ttl, $function) {
$key = apply_filters('fragment_cache_prefix','fragment_cache_').$key;
$output = get_transient($key);
if ( empty($output) ) {
ob_start();
call_user_func($function);
$output = ob_get_clean();
set_transient($key, $output, $ttl);
}
echo $output;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment