DEV Community

Cover image for 5 Real Problems I Hit Building My First Cache-Proof WooCommerce Plugin (And How I Solved Them)
N M Tanim Rahman
N M Tanim Rahman

Posted on Edited on

5 Real Problems I Hit Building My First Cache-Proof WooCommerce Plugin (And How I Solved Them)

Building a WooCommerce estimated delivery date plugin sounds like a weekend project: take today's date, add 3 days, print it under the "Add to Cart" button, and call it a day.

That is what I thought too—until I actually started building Swift Delivery Date for WooCommerce to production standards for the WordPress.org Plugin Directory.

Along the way, I ran into caching traps, timezone bugs, theme CSS clipping, HPOS constraints, and automated directory scanner rejections. Here are the 5 biggest technical problems I hit and the exact engineering solutions I used to fix each one.


Quick Look at the Finished Plugin

3-Step Visual Shipping Timeline Split-Screen Admin Dashboard
3-Step Visual Timeline Split-Screen Admin Dashboard

(Plus a compact **Minimal Delivery Card* preset with custom accent colors for lighter themes:)*

Minimal Delivery Card


Problem 1: Full-Page Caching Freezes Delivery Dates & Countdowns

What went wrong

On a local dev site, PHP calculates the delivery date and cut-off countdown on every page load—everything looks accurate.

The moment you put a real WooCommerce store behind WP Rocket, LiteSpeed Cache, or Cloudflare, PHP stops running on every request. The cached HTML serves a frozen "Order within 4h 12m" badge to shoppers hours later—or worse, still displays yesterday's dispatch date after midnight.

Why the obvious fix fails

A common workaround is calculating everything in frontend JavaScript using new Date(). That breaks immediately because new Date() reads the shopper's local device clock and timezone, not the warehouse's timezone. A shopper in another timezone (or with a slightly wrong system clock) gets the wrong cut-off window.

How I solved it

I built an optional Cache Compatibility Mode backed by a dedicated, lightweight REST API endpoint:

GET /wp-json/wedc/v1/estimate?product_id=123&variation_id=0
Enter fullscreen mode Exit fullscreen mode

The endpoint explicitly sends Cache-Control: no-store, no-cache, must-revalidate, max-age=0 and returns authoritative server timestamps (server_timestamp, next_cutoff_timestamp) alongside the pre-formatted dates (ordered_date, dispatched_date, delivery_range_text).

On page load, Vanilla JS fetches this tiny JSON payload asynchronously, hydrates the card, and ticks the countdown relative to the server's clock—so full-page caching stays 100% enabled while delivery estimates remain accurate down to the second.


Problem 2: Business-Day Math Gets Ugly Fast (Cut-offs, Weekends & DST)

What went wrong

Real stores do not operate on simple today + 3 days math. I had to support:

  • Separate warehouse processing days and courier min/max transit windows
  • A daily order cut-off time (e.g., orders placed at or after 2:00 PM shift to the next working day)
  • Custom non-working weekends (not every region uses Saturday–Sunday; many stores observe Friday–Saturday or custom off-days)
  • Daylight Saving Time (DST) shifts and leap years

Using PHP's mutable DateTime object or raw Unix timestamp addition (+ 86400) introduces silent off-by-one-hour bugs on DST transition days and accidental state mutations across helper methods.

How I solved it

I isolated all date logic inside a pure PHP class (includes/class-date-calculator.php) built strictly on DateTimeImmutable and WordPress's native wp_timezone(). Every step returns a fresh immutable object rather than mutating shared state, and days are stepped via calendar intervals instead of hardcoded seconds.

To be confident I did not miss an edge case, I wrote a standalone CLI test script (tests/run-tests.php) covering 19 edge-case scenarios—including exact cut-off minute boundaries, weekend rollovers, zero-day processing, and DST shifts:

php tests/run-tests.php
Enter fullscreen mode Exit fullscreen mode

Catching math bugs in a 1-second terminal run saved hours of manual browser testing.


Problem 3: Third-Party Theme CSS Clipped My Card Border Right Before Launch

What went wrong

While capturing storefront screenshots for the plugin listing, I noticed something subtle on the Minimal Delivery Card: even though there was plenty of whitespace on the page, the right border and rounded corner of the card were completely sliced off.

Why it happened

Many WooCommerce themes apply overflow: hidden to the product .summary column. Because my minimal flex row had uncontained inner width and lacked strict box-sizing: border-box isolation across child elements, the card overflowed its parent container by just a few pixels—and the theme quietly clipped the right edge.

How I solved it

Instead of trusting any theme's global CSS reset, I hardened the plugin's scoped stylesheet (assets/css/frontend.css):

  1. Enforced box-sizing: border-box, width: 100%, and max-width: 100% on the root wrapper and all descendants.
  2. Added flex-wrap: wrap to the inner delivery-date and countdown-pill row so narrow mobile viewports or tight theme columns wrap gracefully instead of pushing outside the container.

Lesson learned: never assume a WordPress theme's product summary column is wider than your card, and always inspect your UI at multiple zoom levels.


Problem 4: Supporting Modern WooCommerce (HPOS, Variations & Zero Bloat)

What went wrong

Two subtle WooCommerce pitfalls catch a lot of new plugins:

  1. Legacy Order Meta Breaks HPOS: Writing order delivery snapshots with update_post_meta() fails or triggers warnings on stores running WooCommerce's High-Performance Order Storage (HPOS).
  2. Static Estimates Lie on Variable & Out-of-Stock Products: Showing a shipping timeline on a virtual download, an out-of-stock variation, or an unselected variation creates customer confusion.
  3. Heavy Admin Tooling: Pulling in React or jQuery just for a settings screen adds unnecessary build overhead for a lightweight utility plugin.

How I solved it

  • HPOS-Safe Snapshots: Declared official HPOS compatibility and persisted each order's estimated delivery window as immutable metadata using WooCommerce's CRUD APIs—so editing global store rules next month never alters historical order records.
  • Dynamic Variation Hooks: Hooked into WooCommerce's variation events in Vanilla JS so the widget hides cleanly for virtual, downloadable, out-of-stock, or backorder items and updates automatically when shoppers switch variations.
  • Zero-Dependency Split-Screen Dashboard: Built the admin settings page with pure CSS Grid and lightweight Vanilla JS so merchants get a live side-by-side storefront preview (colors, labels, presets) with zero external JS libraries.
  • Developer Hook: Added a clean filter so agencies can override delivery windows per product or category without hacking core files:
add_filter( 'wedc_product_delivery_rule', function ( array $rule, int $product_id, \WC_Product $product ): array {
    if ( $product_id === 42 ) {
        $rule['processing_days'] = 3;
    }
    return $rule;
}, 10, 3 );
Enter fullscreen mode Exit fullscreen mode

Problem 5: Failing the First Automated WordPress.org Scan (TextDomainMismatch)

What went wrong

Right after submitting my first .zip to the WordPress.org Plugin Directory, the automated scanner flagged a TextDomainMismatch issue. My plugin slug assigned by WordPress.org (swift-delivery-date-for-woocommerce) did not match the shorter text domain I had originally used in the plugin header and translation calls.

On top of that, I needed a clean boundary between what belongs in a developer portfolio repo (like tests/run-tests.php and README.md) versus what should actually ship inside the production WordPress.org .zip.

How I solved it

  1. Standardized the Text Domain header and every __() / esc_html__() call across the codebase to match the exact assigned slug (swift-delivery-date-for-woocommerce).
  2. Ran the entire plugin through the official WordPress Plugin Check tool—fixing every strict sanitization, escaping, nonce, and capability check until it returned 0 errors and 0 warnings.
  3. Separated the distribution workflow: GitHub hosts the full engineering repository (including the automated test suite and README.md), while the production release .zip stays lean for end users and WordPress.org reviewers.

What's Next?

The plugin is currently in the Awaiting Review queue on WordPress.org, and the full v1.0.0 source code + installable .zip is open-source on GitHub:

👉 GitHub Repository: tanimra75/swift-delivery-date-for-woocommerce

If you have built WooCommerce plugins or dealt with full-page caching headaches before, I'd love to hear how you approached it—or any feedback you spot in the codebase before v1.1. Drop a comment below!

Top comments (5)

Collapse
 
userxnom profile image
Abdullah Naseer •

Problem 1 is the one I'd steal first — the cached page carries the shell and the live numbers come from a no-store endpoint. And the detail that the countdown ticks locally after a single fetch, instead of polling every second, is the restraint that keeps it cheap.

Problem 2 is the one that would have bitten me. Nineteen edge-case scenarios in a 1-second CLI run is exactly the right weapon for date math — the browser is where that kind of bug hides until a customer in another timezone finds it.

One question on the countdown: after the fetch, do you anchor the ticking to the server_timestamp you just received, or to the device clock? You already rejected new Date() for the dates because a shopper's clock can't be trusted — the same logic would seem to apply to the countdown ticking down. How does the tick stay honest if the shopper's clock is wrong?

Collapse
 
nmtanimrahman_75 profile image
N M Tanim Rahman •

It's anchored to server_timestamp, never compared directly against the shopper's wall clock.

When the response lands, I snapshot anchorClientMs = Date.now() alongside server_timestamp and next_cutoff_timestamp. On each tick, I only measure elapsed time since that anchor:


js
const elapsedSec = Math.floor((Date.now() - state.anchorClientMs) / 1000);
const currentServerTs = state.serverTs + elapsedSec;
const remaining = state.cutoffTs - currentServerTs;
Enter fullscreen mode Exit fullscreen mode
Collapse
 
userxnom profile image
Abdullah Naseer •

That's the clean version of the fix — anchoring to server_timestamp and only ever measuring elapsed time since the anchor means the shopper's clock never gets a vote. The edge I'd want to see handled is what happens when the cutoff passes while the shopper is still on the page: does the countdown flip to the next working day's cutoff, or does it sit at zero until the next fetch?

Thread Thread
 
nmtanimrahman_75 profile image
N M Tanim Rahman •

It automatically flips to the next working day!

When remaining <= 0, the interval stops, sets the display to 00h 00m 00s, and fires a single guarded refreshFromServer() call (protected by an expiredHandled flag so it can never enter a retry loop). Once the fresh payload lands, it updates the dispatch/delivery dates in the DOM, re-anchors serverTs and cutoffTs, and restarts the countdown for the next working day's cutoff. If the request fails offline, it fails silently at 00h 00m 00s instead of hammering the endpoint.

Collapse
 
robertpaschal profile image
Odinaka Robert Nnamani •

today plus three days misses the cut-offs, the weekends and the dst shifts. nineteen edge cases hiding in one line of date math.