Smart Speculative Loading for WordPress 6.8+

Why it’s new and useful:
WordPress 6.8 introduced support for the Speculation Rules API, which enables browsers to preload and even prerender pages the user is likely to visit next. This snippet auto-injects a smart speculation rules script, excluding sensitive URLs like the cart or checkout, so your site loads faster without risking unnecessary resource use or privacy issues

1. Add the Snippet to Your Theme’s functions.php or a Custom Plugin

// Enable smart speculative loading with Speculation Rules API in WordPress 6.8+
add_action('wp_footer', function() {
    // Exclude sensitive URLs (e.g., cart, checkout)
    $excluded = [
        site_url('/cart'),
        site_url('/checkout'),
        // Add more URLs as needed
    ];
    ?>
    <script type="speculationrules">
    {
      "prerender": [
        {
          "source": "document",
          "where": {
            "and": [
              {"not": [{"url": <?php echo json_encode($excluded); ?> }]}
            ]
          },
          "action": "prerender"
        }
      ]
    }
    </script>
    <?php
});
PHP

2. What Does This Do?

  • Automatically enables speculative loading for all internal links, except those you specify (like cart/checkout pages).
  • Improves perceived site speed—pages load instantly when users click links.
  • Uses the latest browser tech (Speculation Rules API) introduced in WordPress 6.86.
  • No plugin required—just a lightweight snippet.

3. How to Customize

  • Add or remove URLs in the $excluded array to control which pages should not be preloaded or prerendered.
Share this snippet!