W3 Total Cache Fragment Caching in WordPress
W3 Total Cache, also known as W3TC, is a very powerful caching plugin for WordPress which is notoriously slow without tuning. For guest users much of your content will typically be static which makes serving up cached content to these users a pretty good idea. But what if you want part of the page to be be dynamic while most of the page is cached? Fragment caching to the rescue.
Configure W3 Total Cache
First you will need to make sure W3TC is properly configured for fragment caching. To enable it, from your WordPress Admin, visit
Performance > General Settings and look under the
Page Cache section. Make sure that the
Page cache method is set to
Disk: Basic and save your settings.
Performance > Page Cache and scroll down to the
Advanced section. Here you will need to check the box next to
Late initialization to enable it. Notice the help text under it:
Enables support for WordPress functionality in fragment caching for the page caching engine. Use of this feature may increase response times.
Set W3TC_DYNAMIC_SECURITY Constant
For security reasons W3TC requires that you create a constant named
W3TC_DYNAMIC_SECURITY and pass it to the sections of code you would like it to ignore (and execute!). An obvious choice for this is
wp-config.php, but you might also have success with
/wp-content/mu-plugins, a custom plugin, your theme’s
functions.php, or even inline before your fragment – though the latter isn’t really recommended. You can set this to a hardcoded value, or use something random for each request.
define( 'W3TC_DYNAMIC_SECURITY', 'SOME_SECURE_STRING_YOU_CREATE' );
Update your template
The final step is to update your template files to indicate where you want W3TC to *not* cache the page. This is done by using an HTML comment called `
mfunc`. You pass it your
W3TC_DYNAMIC_SECURITY and include any PHP you want to execute (without
<!--mfunc <?php echo W3TC_DYNAMIC_SECURITY; ?> --> echo 'The time is '.date( 'H:i:s', time() ); <!--/mfunc <?php echo W3TC_DYNAMIC_SECURITY; ?> -->