<?php
if ( ! defined( 'WP_CACHE' ) || WP_CACHE !== true )
	return;

function do_cache_template_file( $template ) {
	$template_files = array(
		'sidebar.php'
	);

	if ( in_array( $template, $template_files ) )
		return true;
	else
		return false;
}

add_filter( 'pre_load_template', 'maybe_deliver_cache', 10, 3 );
function maybe_deliver_cache( $stop, $template, $require_once ) {
	$template = basename( $template );

	if ( ! do_cache_template_file( $template ) )
		return $stop;

	if ( $html = wp_cache_get( $template, 'theme' ) ) {
		echo "<!-- Start Cached {$template} -->\n{$html}\n<!-- End Cached {$template} -->\n";
		$stop = true;
	}

	return $stop;
}

add_action( 'load_template_pre_require', 'start_load_template_cache', 10, 2 );
function start_load_template_cache( $template, $require_once ) {
	$template = basename( $template );
	if ( ! do_cache_template_file( $template ) )
		return;
	ob_start();
}

add_action( 'load_template_post_require', 'end_load_template_cache', 10, 2 );
function end_load_template_cache( $template, $require_once ) {
	$template = basename( $template );
	if ( ! do_cache_template_file( $template ) )
		return;

	global $batcache;
	$html = ob_get_contents();
	echo $html;
	wp_cache_set( $template, $html, 'theme', isset( $batcache->max_age ) ? $batcache->max_age : 3600 );
}
