Skip to content

Instantly share code, notes, and snippets.

@bcole808
Created March 5, 2014 17:23
Show Gist options
  • Save bcole808/9371883 to your computer and use it in GitHub Desktop.
Save bcole808/9371883 to your computer and use it in GitHub Desktop.
Wordpress template part caching system. Allows parts of a Wordpress template to be stored as site transients in order to speed up the rendering of your theme template parts.
<?php
/**
* Retrieves a template part and caches the output to speed up site
* NOTE: Because we are caching display of posts, we need to make sure to delete the transients when posts are updated or published that might affect these template parts.
*
* Uses this function in conjunction with the WP cache: http://codex.wordpress.org/Function_Reference/get_template_part
*
* @param $slug (string) (required) The slug name for the generic template.
* @param $name (string) (optional) The name of the specialized template.
* @return (string) HTML output of the template part.
*/
if (!function_exists('get_cached_template_part')) {
function get_cached_template_part($slug, $name = '', $ttl = 3600, $sitewide = false) {
if (strlen($name) > 0) {
$transient_id = $slug.'-'.$name;
} else {
$transient_id = $slug;
}
$cached_template_part = ($sitewide) ? get_site_transient( $transient_id ) : get_transient( $transient_id );
if ( false === $cached_template_part ) {
ob_start();
get_template_part($slug,$name);
$cached_template_part = ob_get_contents();
ob_end_clean();
if ($sitewide) {
set_site_transient( $transient_id, $cached_template_part, $ttl );
} else {
set_transient( $transient_id, $cached_template_part, $ttl );
}
}
echo $cached_template_part;
return true;
}
}
?>
@eduardo-marcolino
Copy link

Thanks for post this man!

@szepeviktor
Copy link

If you use object cache click here: https://github.com/szepeviktor/tiny-cache

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