Implementing Page Fragment Caching in W3 Total Cache

Page fragment caching is a must-have function for cache plugins like W3 Total Cache, it’s a shame that such functions didn’t get much attention.

W3 Total Cache answered the “How do I implement page fragment caching?” question in the Developers section in their plugin FAQ page:

First you need to define W3TC_DYNAMIC_SECURITY in your wp-config.php file.

define('W3TC_DYNAMIC_SECURITY', 'somesecurestring');

Edit your templates with the following syntax to ensure that dynamic features remain so. Replace W3TC_DYNAMIC_SECURITY with content of the constant or use echo to print constant:

Example 1:
<!-- mfunc W3TC_DYNAMIC_SECURITY any PHP code --><!-- /mfunc W3TC_DYNAMIC_SECURITY -->
Example 2:
<!-- mfunc W3TC_DYNAMIC_SECURITY -->any PHP code<!-- /mfunc W3TC_DYNAMIC_SECURITY -->
Example 3:
echo rand();
<!--/mfunc W3TC_DYNAMIC_SECURITY -->
Example 4:
<!-- mclude W3TC_DYNAMIC_SECURITY path/to/file.php --><!-- /mclude W3TC_DYNAMIC_SECURITY -->
Example 5:
<!-- mclude W3TC_DYNAMIC_SECURITY -->path/to/file.php<!-- /mclude W3TC_DYNAMIC_SECURITY -->
Be aware that WordPress functions will not be available.

The answer itself is pretty much clear except it forgot to mention a most important step: YOU NEED TO ADD ‘mfunc’ TO THE ‘Ignored comment stems’ SETTINGS.

Source: WooThemes

Without this step you’ll waste 100 hours on testing the page fragment caching and never getting it worked. Thanks to WooThemes pointed it out and hope I can save someone else’s 100 hours.

Added on March 27:

After couple of days I found the fragment caching still acted weird. Sometimes it worked fine but sometimes didn’t. After some research I believe it’s related to the “Page cache method” I set.

The site I need to implement fragment caching is sometimes very high volume. So if I set the “Page cache method” to “Disk: Enhanced”, which is recommended by W3TC, the old cache files would be used while the new cache files are being generating. Read explanation here. Changed the setting to “Disk: Basic” can fix the issue.

The other thing to note is if you need to use WordPress functions in your fragment caching block, you should enable the “Late initialization”, which may increase response time.

Now the fragment caching finally worked on my client’s website. I highly recommend anyone who needs a powerful WordPress cache plugin, just go with W3 Total Cache. WP-Rocket is great but it doesn’t support fragment cache yet.