Created
October 8, 2019 13:27
-
-
Save edlefebvre/390ba10773a8ac2b2807f9f268715e56 to your computer and use it in GitHub Desktop.
Fragment caching function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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