Created
March 5, 2014 17:23
-
-
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.
This file contains 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 | |
/** | |
* 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; | |
} | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for post this man!