W3 Total Cache – Fragment Caching

W3 Total Cache is a great plugin for speeding up your WordPress website with page cache, database cache, minifying JS and CSS, object cache, content delivery network and more.

A problem could arise with dynamic code and a certain part of code might be cached with W3 Total Cache which you don’t want to cache. You can use the MFUNC fragment caching in your code to prevent this.

Using W3 Total Cache MFUNC Fragment Caching

W3 Total Cache lets you use it’s MFUNC fragment caching to specify cached and not-cached content but it also requires a W3TC_DYNAMIC_SECURITY constant for security reasons.

In addition to that, two things are required in order to use fragment caching:

  1. Set the page cache to Disk: Basic
  2. Turn on late initialisation under the Page Cache settings section.

Here is an example of using W3TC MFUNC comments:

CODE 1 above is the code to execute with W3TC enabled and the page currently cached.

CODE 2 above is the code to execute with W3TC disabled or the page not cached.

Of course, in the above example CODE1 and CODE2 will most likely be the same code.

For example, say you have PHP code that echoes “This is my website”. You can implement it like this using W3 Total Cache mfunc fragment caching:

Dynamic HTML content fragment caching

If your dynamic content is not specifically PHP but rather HTML mixed with PHP, CSS, Javascript and other things, you’ll follow the same process but you can actually close the PHP tags inside MFUNC and then output your HTML with whatever is inside it and then open the PHP tags again. Here is an example:

Good luck with it!



  1. what about plugins? I have a problem, I am using qtranslate and I have to enable late init so that qtranslate works, how can I make so that qtranslate and other cookie dependent plugins execute before cached page is served?

    • You’ll have to discuss this with the authors/developers of those individual plugins. The article just illustrates W3 Total Cache fragment caching to developers who may want to use it.

  2. Does this only work with Pro version of W3TC?

  3. I can’t understand what code is needed to add in MFUNC comments ! Is it required ?
    Or just to see whether it’s working or not ?

  4. W3TC_DYNAMIC_SECURITY should have a static value, not a dynamic value. Using a dynamic value will cause issues because the plugin will check for comments matching that variable. If the variable is dynamic, it will check for a new value that doesn’t match the value in cached pages.

Leave a Reply

Your email address will not be published.


© 2021 Contrid

Theme by Anders NorénUp ↑

Pin It on Pinterest

%d bloggers like this: