While implementing fragment caching on a wordpress site by using the technique described here: http://css-tricks.com/wordpress-fragment-caching-revisited/ I found that it seems to actually increase queries.
I have now cached many fragments on the page, and (in my local environment) I get 294 queries in 0.764 seconds (calculated with get_num_queries()
and timer_stop(0)
).
One snippet I've cached is the menu. If I remove fragment caching from it, I get: 292 queries in 0.736 seconds.
If I remove fragment caching from my search from: 290 queries in 0.862 seconds.
And if I remove more queries: 287 queries in 0.783 seconds.
So, what's happening here? Fragment caching is definitely working, but is it having a positive effect? Also, is it ok to have actually more queries with fragment caching than without?
In functions.php
I have:
function fragment_cache($key, $ttl, $function) {
if ( is_user_logged_in() ) {
call_user_func($function);
return;
}
$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;
}
In my post page
<?php fragment_cache('text' . $post->ID, WEEK_IN_SECONDS, function() { ?>
<?php the_sub_field('text'); ?>
<?php }); ?>
In my menu:
<?php
fragment_cache('primary-nav', YEAR_IN_SECONDS, function() {
wp_nav_menu( array( 'theme_location' => 'primary' ) );
});
?>