DEV Community

3K Home Warehouse
3K Home Warehouse

Posted on

Deterministic Shortcode Cache Keys and Versioned Invalidation in WooCommerce Price Tables

Rendering dynamic product tables via WordPress shortcodes is convenient for merchandising teams, because an editor can drop [wpdpl_price_table cat="laminate-12mm" brand="brand-a" sort="sku"] onto any landing page without touching theme templates. The trouble shows up once a catalog grows past a few hundred variable products and traffic hits a heavily shared price list page.

A naive wp_cache_set() or set_transient() wrapper around shortcode output usually breaks in two predictable ways:

  1. Key fragmentation: [wpdpl_price_table cat="a" sort="sku"] and [wpdpl_price_table sort="sku" cat="a"] produce different serialized strings even though they query the exact same data.
  2. Orphaned keys on product update: calling delete_transient() for every possible attribute combination when a single WooCommerce SKU changes price is fragile, and running DELETE FROM wp_options WHERE option_name LIKE '_transient_wpdpl_%' locks the options table on busy sites.

When maintaining the live product catalog behind the 3K Home flooring price list, we switched to a deterministic key builder paired with an integer namespace version. That eliminated manual wildcard purges while keeping cache hits predictable.

Step 1: Canonicalize Shortcode Attributes Before Hashing

Before generating a cache key, merge defaults via shortcode_atts(), cast scalar types consistently, trim whitespace, lowercase enum values, and sort keys alphabetically (ksort). That guarantees semantically identical shortcodes always resolve to one hash.

<?php
declare(strict_types=1);

function wpdpl_build_cache_key(array $raw_atts, int $version): string {
    $defaults = [
        'cat'      => '',
        'brand'    => '',
        'per_page' => 50,
        'sort'     => 'menu_order',
        'currency' => 'VND',
    ];

    $atts = shortcode_atts($defaults, $raw_atts, 'wpdpl_price_table');

    $normalized = [
        'brand'    => strtolower(trim((string) $atts['brand'])),
        'cat'      => strtolower(trim((string) $atts['cat'])),
        'currency' => strtoupper(trim((string) $atts['currency'])),
        'per_page' => max(1, min(200, (int) $atts['per_page'])),
        'sort'     => strtolower(trim((string) $atts['sort'])),
    ];

    ksort($normalized);

    $hash = substr(hash('sha256', wp_json_encode($normalized)), 0, 16);
    return sprintf('wpdpl_tbl_v%d_%s', $version, $hash);
}
Enter fullscreen mode Exit fullscreen mode

Keep the final key under 172 characters (WordPress truncates transient names at 172 bytes in wp_options). A 16-hex-character SHA-256 prefix keeps the key compact while avoiding collisions across typical catalog combinations.

Step 2: Version-Bump Invalidation Instead of Wildcard Deletes

Rather than tracking every rendered key in an index array (which introduces race conditions under concurrent writes), store a single integer option such as wpdpl_cache_version.

  • Every read fetches the current version integer (cached automatically in WordPress alloptions or Redis object cache) and embeds it into the key name.
  • Whenever a WooCommerce product, variation, or relevant taxonomy term changes, increment wpdpl_cache_version by 1.
  • Old keys become unreachable immediately and expire naturally via TTL without any LIKE table scan.
<?php
function wpdpl_get_cache_version(): int {
    return max(1, (int) get_option('wpdpl_cache_version', 1));
}

function wpdpl_bump_cache_version(): void {
    $next = wpdpl_get_cache_version() + 1;
    update_option('wpdpl_cache_version', $next, true);
}

add_action('woocommerce_update_product', 'wpdpl_bump_cache_version');
add_action('woocommerce_update_product_variation', 'wpdpl_bump_cache_version');
add_action('edited_product_cat', 'wpdpl_bump_cache_version');
Enter fullscreen mode Exit fullscreen mode

Important edge case: during bulk CSV imports, WooCommerce fires woocommerce_update_product hundreds of times in one request. Wrap wpdpl_bump_cache_version() with a static per-request guard (static $bumped = false;) so an import increments the option once instead of hammering wp_options on every row.

Step 3: Guard Against Cache Stampedes on Cold Keys

When a version bump invalidates a popular price table during peak traffic, 20 concurrent requests can miss cache simultaneously and execute the exact same heavy WP_Query + variation price loop.

If you have a persistent object cache (Redis or Memcached), wp_cache_add() acts as an atomic short-lived lock:

<?php
function wpdpl_render_cached_table(array $raw_atts): string {
    $version = wpdpl_get_cache_version();
    $key     = wpdpl_build_cache_key($raw_atts, $version);
    $group   = 'wpdpl_tables';

    $cached = wp_cache_get($key, $group);
    if (is_string($cached)) {
        return $cached;
    }

    $lock_key = $key . '_lock';
    $got_lock = wp_cache_add($lock_key, 1, $group, 15);

    if (!$got_lock) {
        // Serve previous version briefly if available, avoiding stampede
        $stale = wp_cache_get(wpdpl_build_cache_key($raw_atts, max(1, $version - 1)), $group);
        if (is_string($stale)) {
            return $stale;
        }
    }

    $html = wpdpl_query_and_render_html($raw_atts);
    wp_cache_set($key, $html, $group, 6 * HOUR_IN_SECONDS);

    if ($got_lock) {
        wp_cache_delete($lock_key, $group);
    }

    return $html;
}
Enter fullscreen mode Exit fullscreen mode

Serving version - 1 for a few hundred milliseconds while one worker rebuilds version gives you stale-while-revalidate semantics in roughly 30 lines of plain WordPress PHP, with zero extra Composer dependencies.

Practical Checklist Before Deploying

  • Separate logged-in pricing: if B2B or wholesale users see different prices, include the normalized role tier inside $normalized before hashing.
  • Avoid wp_options bloat: if the site does not run Redis/Memcached and falls back to database transients, keep TTL reasonable (1 to 6 hours) and verify WP-Cron actually cleans expired transients.
  • Instrument hit/miss headers in staging: add a temporary <!-- wpdpl-cache: hit v14 --> comment on staging to confirm attribute reordering hits the same cache entry.

How are you invalidating shortcode fragments on WooCommerce catalogs without paying the cost of full-page cache flushes on every stock update?

Top comments (0)