Last updated on

When implementing a Page Fragment Caching Exception, you are telling W3 Total Cache to bypass cache for a particular section of content. A great use case for this is dynamic content that you wish to update in real time, separate from the page caching itself. The following article will walk you through the process.

As of W3 Total Cache 2.10.0, Page Fragment Cache tags work differently. Instead of placing PHP or a file path inside the tag, you register a callback once and reference it from the tag by name. W3 Total Cache runs only your registered callback when it serves the cached page. Tags from older versions that still contain raw PHP or a file path are no longer run, so they must be migrated using the steps below. (Using a version before 2.10.0? See How to Implement a Page Fragment Caching Exception (versions before 2.10.0).)

Speed Up Your WordPress Website.

A Difference of Just 100ms in Page Load Speeds Can Cause a Visitor to Prefer Your Competitor’s Website.

  • Select your page cache method in Performance → General Settings
  • Enable “late initialization” on the Page Cache settings page
  • Add define('W3TC_DYNAMIC_SECURITY', 'mycode'); to your wp-config.php file (change mycode to your own unique value)
  • Register a callback for each fragment using the w3tc_dynamic_callbacks filter

And finally, use this format to implement the caching exception. First, register the callback in your theme’s functions.php (or a small site plugin):

// functions.php
add_filter(
      'w3tc_dynamic_callbacks',
      function ( $callbacks ) {
              $callbacks['my_fragment'] = function ( $args, $kind ) {
                      // Return the dynamic HTML for this fragment.
                      // $args = JSON from the tag (decoded to an array); $kind = 'mfunc' or 'mclude'.
                      return somefunction();
              };
              return $callbacks;
      }
);

Then emit the tag in your template where the dynamic content should appear, referencing the callback by name with call:<slug>. W3 Total Cache adds the integrity signature automatically, so you never write it yourself:

<!-- mfunc mycode call:my_fragment {} --><!-- /mfunc mycode -->

Your callback must return a string of HTML (don’t echo). To pass data into a fragment, include JSON in the tag — for example call:my_fragment {"id":42} — and read $args['id'] in the callback. mclude works the same way: register a slug that returns the included output (for example with ob_start() / ob_get_clean()) and reference it with call:<slug>; raw file paths are no longer included directly. If you use Minify, add mfunc and mclude to the Ignored comment stems setting. Third-party plugins or themes that shipped their own legacy tags must adopt this same filter — a site owner cannot re-enable the old in-tag-code behavior.


Implementing a Page Fragment Caching Exception for Comments in Twenty Twenty

The following example demonstrates how to render blog post comments dynamically on an otherwise cached page using the default WordPress theme, Twenty Twenty, and W3 Total Cache 2.10.0 or later.

Resources:

  • Twenty Twenty theme
  • Twenty Twenty child theme

Install both themes in your WordPress installation and activate the Twenty Twenty child theme.

Copy the comments.php file from the Twenty Twenty theme over to the child theme root directory.

Install and activate W3 Total Cache and set your Pro license.

Navigate to Performance > General Settings and enable Page Cache. If you do not have memory based caching available on your server (Redis or Memcached) then select Disk: Basic for the Page Cache Method. (Disk: Enhanced is not supported for fragment exceptions.)

Access your Page Cache settings by navigating to Performance > Page Cache in your WordPress dashboard and enable Late initialization under the Advanced section.

Add the code define(‘W3TC_DYNAMIC_SECURITY’, ‘comments’); to the wp-config.php file associated with your website just before the line /* That’s all, stop editing! Happy publishing. */

Register the comments callback by adding the following to your child theme’s functions.php file:

// Twenty Twenty child theme — functions.php
add_filter(
      'w3tc_dynamic_callbacks',
      function ( $callbacks ) {
              $callbacks['comments_list'] = function ( $args, $kind ) {
                      ob_start();
                      wp_list_comments(
                              array(
                                      'walker'      => new TwentyTwenty_Walker_Comment(),
                                      'avatar_size' => 120,
                                      'style'       => 'div',
                              )
                      );
                      return ob_get_clean();
              };
              return $callbacks;
      }
);

Open comments.php located in your child theme directory using your preferred text editor. Locate the wp_list_comments call and replace it with the matching tag, which references the callback you just registered. Your code should look like this:

<!-- mfunc comments call:comments_list {} --><!-- /mfunc comments -->

 

W3 Total Cache

You haven't seen fast until you've tried PRO

   Full Site CDN + Additional Caching Options
   Advanced Caching Statistics, Purge Logs and More

Everything you need to scale your WordPress Website and improve your PageSpeed.

Leave a Reply

Your email address will not be published. Required fields are marked *

W3 Total Cache logo

We Can Help Optimize Your Website

Optimize your site’s performance with our one-time premium services or ongoing monthly VIP support. View services

Got a Minute?

Your feedback helps us improve. Complete our customer survey now.

Partners

Bunny CDN Logo