Skip to content

Instantly share code, notes, and snippets.

@westonruter
Forked from markjaquith/gist:2653957
Last active August 12, 2021 07:00
Show Gist options
  • Star 15 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save westonruter/5475349 to your computer and use it in GitHub Desktop.
Save westonruter/5475349 to your computer and use it in GitHub Desktop.
WordPress Fragment Caching convenience wrapper
<?php
/*
Usage:
cache_fragment_output( 'unique-key', 3600, function () {
functions_that_do_stuff_live();
these_should_echo();
});
*/
function cache_fragment_output( $key, $ttl, $function ) {
$group = 'fragment-cache';
$output = wp_cache_get( $key, $group );
if ( empty($output) ) {
ob_start();
call_user_func( $function );
$output = ob_get_clean();
wp_cache_add( $key, $output, $group, $ttl );
}
echo $output;
}
@markjaquith
Copy link

Two reasons I didn't do it this way (I feel like I've said this before, but maybe it was to someone else):

  1. Requires PHP 5.3 — I wanted "runs on any WordPress install" code.
  2. Would likely require re-working the output code, if there is any reliance on global variables. I wanted something I could wrap around some random theme code and know that it would work every time.

But I agree that this is cleaner.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment