<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[ThreeK Home Engineering]]></title><description><![CDATA[ThreeK Home Engineering]]></description><link>https://kho3khome.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Fri, 04 Dec 2026 23:28:07 GMT</lastBuildDate><atom:link href="https://kho3khome.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Eliminating N+1 Postmeta Queries When Rendering Multi-Attribute Flooring Price Matrices in WooCommerce]]></title><description><![CDATA[Variable products in WooCommerce work well on a single product detail page where you inspect four to eight variations of one item. Problems start when you…]]></description><link>https://kho3khome.hashnode.dev/eliminating-n-1-postmeta-queries-when-rendering-multi-attribute-flooring-price-matrices-in-woocommerce</link><guid isPermaLink="true">https://kho3khome.hashnode.dev/eliminating-n-1-postmeta-queries-when-rendering-multi-attribute-flooring-price-matrices-in-woocommerce</guid><category><![CDATA[woocommerce]]></category><category><![CDATA[WordPress]]></category><category><![CDATA[PHP]]></category><category><![CDATA[MySQL]]></category><category><![CDATA[performance]]></category><dc:creator><![CDATA[3K Home Warehouse]]></dc:creator><pubDate>Fri, 04 Dec 2026 08:20:01 GMT</pubDate><content:encoded><![CDATA[<p>Variable products in WooCommerce work well on a single product detail page where you inspect four to eight variations of one item. Problems start when you build a category-wide quotation matrix that lists 80 variable flooring lines on one screen, each carrying thickness (<code>8mm</code>, <code>12mm</code>), wear class (<code>AC4</code>, <code>AC5</code>), and surface finish variations.</p>
<p>Calling <code>$product-&gt;get_available_variations()</code> inside a loop over 80 parent products triggers hundreds of individual <code>WC_Product_Variation</code> object instantiations, gallery lookups, tax calculations, and <code>wp_postmeta</code> reads. Even with local PHP memory caching, an uncached request easily crosses 1,200 SQL queries and 1.8 seconds of server time.</p>
<p>When maintaining live multi-category quotation pages (such as the <a href="https://3khome.com/bang-gia/">flooring price schedule at 3K Home</a>), replacing object-heavy variation loops with a two-query batched hydration pattern cuts SQL count to a flat constant regardless of how many SKUs appear on the page.</p>
<h2>Why <code>get_available_variations()</code> Hurts on Matrix Pages</h2>
<p>Inside WooCommerce core, <code>WC_Product_Variable::get_available_variations()</code> prepares full frontend JSON payloads designed for the single-product add-to-cart script:</p>
<ol>
<li>It instantiates a <code>WC_Product_Variation</code> object for every child post ID.</li>
<li>It resolves attachment metadata (<code>wp_get_attachment_image_src</code>) for variation thumbnails even if your quotation table only prints text rows.</li>
<li>It evaluates stock availability HTML, purchasability hooks, and shipping weight formatting per child variation.</li>
</ol>
<p>For a read-only specification and price matrix, you typically need only five fields per child variation: <code>ID</code>, <code>post_parent</code>, <code>_sku</code>, <code>_price</code> (or <code>_regular_price</code> / <code>_sale_price</code>), and <code>attribute_pa_*</code> meta keys.</p>
<h2>Step 1: Fetch Published Child Variations in One <code>IN (...)</code> Query</h2>
<p>Suppose your shortcode receives an array of variable parent product IDs (<code>$parent_ids</code>) from a lightweight category query (<code>'fields' =&gt; 'ids'</code>). Fetch all published variation post rows in a single prepared query:</p>
<pre><code class="language-php">&lt;?php
declare(strict_types=1);

/**
 * @param int[] $parent_ids
 * @return array&lt;int, array{id:int, parent_id:int, menu_order:int}&gt;
 */
function wpdpl_fetch_variation_posts(array $parent_ids): array {
    global $wpdb;

    $clean_ids = array_values(array_unique(array_filter(array_map('absint', $parent_ids))));
    if ($clean_ids === []) {
        return [];
    }

    $placeholders = implode(',', array_fill(0, count($clean_ids), '%d'));
    $sql = $wpdb-&gt;prepare(
        "SELECT ID, post_parent, menu_order
         FROM {$wpdb-&gt;posts}
         WHERE post_type = 'product_variation'
           AND post_status = 'publish'
           AND post_parent IN ($placeholders)
         ORDER BY post_parent ASC, menu_order ASC, ID ASC",
        ...$clean_ids
    );

    $rows = $wpdb-&gt;get_results($sql, ARRAY_A) ?: [];
    $variations = [];
    foreach ($rows as $row) {
        $vid = (int) $row['ID'];
        $variations[$vid] = [
            'id'         =&gt; $vid,
            'parent_id'  =&gt; (int) $row['post_parent'],
            'menu_order' =&gt; (int) $row['menu_order'],
            'sku'        =&gt; '',
            'price'      =&gt; null,
            'attributes' =&gt; [],
        ];
    }

    return $variations;
}
</code></pre>
<h2>Step 2: Hydrate Only the Required Meta Keys in One Pass</h2>
<p>Instead of calling <code>get_post_meta($vid)</code> per variation (or warming the entire <code>wp_postmeta</code> blob including heavy third-party SEO/feed fields), query only <code>_sku</code>, <code>_price</code>, <code>_stock_status</code>, and <code>attribute_%</code> keys for the collected variation IDs:</p>
<pre><code class="language-php">&lt;?php
declare(strict_types=1);

/**
 * @param array&lt;int, array&lt;string, mixed&gt;&gt; $variations Indexed by variation ID.
 * @return array&lt;int, list&lt;array&lt;string, mixed&gt;&gt;&gt; Grouped by parent product ID.
 */
function wpdpl_hydrate_variation_meta(array $variations): array {
    global $wpdb;

    if ($variations === []) {
        return [];
    }

    $vids = array_keys($variations);
    $placeholders = implode(',', array_fill(0, count($vids), '%d'));

    $sql = $wpdb-&gt;prepare(
        "SELECT post_id, meta_key, meta_value
         FROM {$wpdb-&gt;postmeta}
         WHERE post_id IN ($placeholders)
           AND (
               meta_key IN ('_sku', '_price', '_stock_status')
               OR meta_key LIKE 'attribute\\_%'
           )",
        ...$vids
    );

    $meta_rows = $wpdb-&gt;get_results($sql, ARRAY_A) ?: [];
    foreach ($meta_rows as $m) {
        $vid = (int) $m['post_id'];
        if (!isset($variations[$vid])) {
            continue;
        }
        $key = (string) $m['meta_key'];
        $val = (string) $m['meta_value'];

        if ($key === '_sku') {
            $variations[$vid]['sku'] = $val;
        } elseif ($key === '_price' &amp;&amp; $val !== '') {
            $variations[$vid]['price'] = (float) $val;
        } elseif ($key === '_stock_status') {
            $variations[$vid]['stock_status'] = $val;
        } elseif (str_starts_with($key, 'attribute_')) {
            $attr_name = substr($key, strlen('attribute_'));
            $variations[$vid]['attributes'][$attr_name] = $val;
        }
    }

    $grouped = [];
    foreach ($variations as $item) {
        if ($item['price'] === null) {
            continue;
        }
        $grouped[$item['parent_id']][] = $item;
    }

    return $grouped;
}
</code></pre>
<h2>Step 3: Resolve Human-Readable Term Labels Without Per-Row Term Queries</h2>
<p>Taxonomy-backed attributes store slugs such as <code>12mm</code> or <code>ac4</code> inside <code>wp_postmeta</code>, whereas the table header needs term names (<code>12 mm</code>, <code>AC4 Class 32</code>). Collect all unique taxonomy-slug pairs across <code>$grouped</code> first, prime them via a single <code>get_terms(['taxonomy' =&gt; $taxonomies, 'hide_empty' =&gt; false])</code> call, and build an in-memory <code>[$taxonomy][$slug] =&gt; $name</code> map before rendering HTML.</p>
<pre><code class="language-php">&lt;?php
declare(strict_types=1);

/**
 * @param string[] $taxonomies e.g. ['pa_thickness', 'pa_abrasion_class']
 * @return array&lt;string, array&lt;string, string&gt;&gt;
 */
function wpdpl_build_term_label_map(array $taxonomies): array {
    $terms = get_terms([
        'taxonomy'   =&gt; $taxonomies,
        'hide_empty' =&gt; false,
    ]);

    if (is_wp_error($terms) || !is_array($terms)) {
        return [];
    }

    $map = [];
    foreach ($terms as $term) {
        $map[$term-&gt;taxonomy][$term-&gt;slug] = $term-&gt;name;
    }
    return $map;
}
</code></pre>
<h2>Measured Impact and Caveats</h2>
<p>On a catalog page rendering 75 variable flooring products (310 child variations total):</p>
<ul>
<li><strong>SQL queries per uncached render:</strong> dropped from <code>1,180+</code> down to <code>4</code> queries (parent IDs, child variation posts, targeted <code>wp_postmeta</code>, and taxonomy term map).</li>
<li><strong>Peak PHP memory per worker:</strong> dropped from <code>68 MB</code> down to <code>21 MB</code> because zero <code>WC_Product_Variation</code> instances or image attachment arrays are allocated.</li>
<li><strong>Tax/currency hooks:</strong> Because reading raw <code>_price</code> bypasses <code>woocommerce_product_get_price</code> filters, only use direct SQL hydration when your catalog prices are stored tax-inclusive (or apply your deterministic tax multiplier explicitly in the presenter function). If you rely on dynamic role-based pricing plugins that hook <code>get_price()</code>, cache the rendered HTML fragment per user role tier instead.</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Avoiding Floating-Point Drift When Converting Square-Meter Flooring Prices to Full Boxes in WooCommerce]]></title><description><![CDATA[Most flooring stores quote catalog prices per square meter (m2) because buyers compare materials by area, yet warehouses only ship intact cartons. A…]]></description><link>https://kho3khome.hashnode.dev/avoiding-floating-point-drift-when-converting-square-meter-flooring-prices-to-full-boxes-in-woocommerce</link><guid isPermaLink="true">https://kho3khome.hashnode.dev/avoiding-floating-point-drift-when-converting-square-meter-flooring-prices-to-full-boxes-in-woocommerce</guid><category><![CDATA[WordPress]]></category><category><![CDATA[woocommerce]]></category><category><![CDATA[PHP]]></category><category><![CDATA[TypeScript]]></category><category><![CDATA[ecommerce]]></category><dc:creator><![CDATA[3K Home Warehouse]]></dc:creator><pubDate>Thu, 03 Dec 2026 05:53:43 GMT</pubDate><content:encoded><![CDATA[<p>Most flooring stores quote catalog prices per square meter (<code>m2</code>) because buyers compare materials by area, yet warehouses only ship intact cartons. A typical 12 mm laminate carton might contain 10 planks of <code>1221 mm x 146 mm</code>, which equals <code>1.78266 m2</code> per box.</p>
<p>When you let a WooCommerce frontend calculator divide requested room area by a rounded decimal like <code>1.78</code> in JavaScript and pass that back to PHP checkout totals, subtle rounding mismatches start appearing on orders:</p>
<ul>
<li>A buyer enters <code>35.65 m2</code>. Dividing by <code>1.78266</code> yields <code>19.9982...</code> boxes -&gt; <code>20</code> boxes.</li>
<li>If the theme stores <code>1.78</code> in product meta, <code>35.65 / 1.78 = 20.028...</code> -&gt; <code>21</code> boxes, overcharging by one carton.</li>
<li>Even worse, IEEE-754 binary floats produce classic edge cases such as <code>17.8266 / 1.78266 = 10.000000000000002</code>, where <code>Math.ceil()</code> jumps from <code>10</code> boxes to <code>11</code> boxes for an exact multiple of box area.</li>
</ul>
<p>While standardizing box-coverage calculations across the catalog powering the <a href="https://3khome.com/bang-gia/">3K Home flooring price list</a>, we moved all area math into integer square millimeters (<code>mm2</code>) and kept box quantity as the single source of truth in the WooCommerce cart.</p>
<h2>Store Exact Plank Dimensions in Integer Millimeters</h2>
<p>Instead of saving one pre-rounded float <code>_box_area_m2 = 1.78</code>, store three integer post-meta fields on every flooring product or variation:</p>
<ul>
<li><code>_wpdpl_plank_length_mm</code> (for example <code>1221</code>)</li>
<li><code>_wpdpl_plank_width_mm</code> (for example <code>146</code>)</li>
<li><code>_wpdpl_planks_per_box</code> (for example <code>10</code>)</li>
</ul>
<p>The exact box coverage in <code>mm2</code> is always an exact integer:</p>
<pre><code class="language-php">&lt;?php
declare(strict_types=1);

function wpdpl_get_box_area_mm2(int $length_mm, int $width_mm, int $planks_per_box): int {
    return max(1, $length_mm) * max(1, $width_mm) * max(1, $planks_per_box);
}

function wpdpl_boxes_for_requested_m2(
    float $requested_m2,
    int $length_mm,
    int $width_mm,
    int $planks_per_box,
    int $waste_bps = 0 // basis points: 700 = +7.00%
): array {
    $box_mm2 = wpdpl_get_box_area_mm2($length_mm, $width_mm, $planks_per_box);

    // Convert requested area to integer mm2 (1 m2 = 1_000_000 mm2)
    $net_mm2 = (int) round(max(0.0, $requested_m2) * 1_000_000);

    // Apply waste percentage using integer basis points (avoid float 1.07 drift)
    $target_mm2 = (int) intdiv($net_mm2 * (10_000 + max(0, $waste_bps)) + 9_999, 10_000);

    // Exact integer ceiling division: ceil(target_mm2 / box_mm2)
    $boxes = $target_mm2 &gt; 0 ? (int) intdiv($target_mm2 + $box_mm2 - 1, $box_mm2) : 0;

    return [
        'boxes'          =&gt; $boxes,
        'box_area_mm2'   =&gt; $box_mm2,
        'ordered_m2_str' =&gt; number_format(($boxes * $box_mm2) / 1_000_000, 3, '.', ''),
    ];
}
</code></pre>
<p>Test the exact-multiple edge case (<code>17.8266 m2</code> with <code>1221 x 146 x 10</code>):</p>
<ul>
<li><code>$box_mm2 = 1_782_660</code></li>
<li><code>$net_mm2 = 17_826_600</code></li>
<li><code>intdiv(17_826_600 + 1_782_659, 1_782_660) = 10</code> exact boxes. No floating-point phantom box.</li>
</ul>
<h2>Keep Cart Quantity in Whole Boxes, Derive Line Total Server-Side</h2>
<p>Never trust a client-supplied square-meter price calculation on <code>add_to_cart</code>. Let the WooCommerce cart item quantity represent <strong>integer boxes</strong>, and compute the per-box unit price on the server from the catalog's per-m2 base price:</p>
<pre><code class="language-php">&lt;?php
add_filter('woocommerce_add_cart_item_data', function (array $cart_item_data, int $product_id, int $variation_id): array {
    $target_id = $variation_id ?: $product_id;
    $len  = (int) get_post_meta($target_id, '_wpdpl_plank_length_mm', true);
    $wid  = (int) get_post_meta($target_id, '_wpdpl_plank_width_mm', true);
    $pcs  = (int) get_post_meta($target_id, '_wpdpl_planks_per_box', true);

    if ($len &gt; 0 &amp;&amp; $wid &gt; 0 &amp;&amp; $pcs &gt; 0) {
        $cart_item_data['wpdpl_box_mm2'] = wpdpl_get_box_area_mm2($len, $wid, $pcs);
    }

    return $cart_item_data;
}, 10, 3);
</code></pre>
<p>This keeps inventory decrementing cleanly by physical cartons (<code>stock_quantity</code> = boxes on warehouse pallets), while the cart line item displays both the exact box count (<code>20 boxes</code>) and the covered area (<code>35.653 m2</code>) cleanly for the customer.</p>
<h2>Mirror the Same Integer Logic in Frontend TypeScript</h2>
<p>To guarantee zero discrepancy between the product page calculator and the server checkout total, ship <code>data-plank-l</code>, <code>data-plank-w</code>, and <code>data-planks-per-box</code> attributes to the browser and run the exact same integer formula:</p>
<pre><code class="language-ts">export function calcBoxesInteger(requestedM2: number, lenMm: number, widMm: number, perBox: number, wasteBps = 0): number {
  const boxMm2 = Math.max(1, lenMm) * Math.max(1, widMm) * Math.max(1, perBox);
  const netMm2 = Math.round(Math.max(0, requestedM2) * 1_000_000);
  const targetMm2 = Math.floor((netMm2 * (10_000 + Math.max(0, wasteBps)) + 9_999) / 10_000);
  return targetMm2 &gt; 0 ? Math.floor((targetMm2 + boxMm2 - 1) / boxMm2) : 0;
}
</code></pre>
<p>Because JavaScript safe integers reach <code>9 x 10^15</code> (<code>Number.MAX_SAFE_INTEGER</code>), multiplying areas up to <code>10,000 m2</code> (<code>10^10 mm2</code>) by <code>10,000</code> basis points stays comfortably inside exact integer precision without needing <code>BigInt</code>.</p>
<h2>Trade-offs Worth Noting</h2>
<ul>
<li><strong>Migration of legacy SKUs:</strong> older catalog entries that only recorded <code>_box_area_m2</code> need a fallback conversion (<code>round($legacy_m2 * 1_000_000)</code>) until warehouse dimensions are backfilled.</li>
<li><strong>Currency rounding per box:</strong> when multiplying <code>price_per_m2 * (box_mm2 / 1_000_000)</code>, decide explicitly whether to round each box price to your local invoice rounding step or round only at the line-item subtotal so invoice lines reconcile cleanly with accounting software.</li>
</ul>
<p>For teams building WooCommerce stores that sell tiles, flooring, or wallpaper by area yet ship by box or roll: do you store stock quantities in cartons and display per-m2 labels, or store stock in fractional square meters?</p>
]]></content:encoded></item><item><title><![CDATA[Modeling Herringbone Left/Right (A/B) Plank Packs and Centerline Shift in a Flooring Calculator (v0.4-wip)]]></title><description><![CDATA[In our v0.3 flooring calculator update, we left one clear open question on the table: how should an estimation utility model click-lock herringbone…]]></description><link>https://kho3khome.hashnode.dev/modeling-herringbone-left-right-a-b-plank-packs-and-centerline-shift-in-a-flooring-calculator-v0-4-wip</link><guid isPermaLink="true">https://kho3khome.hashnode.dev/modeling-herringbone-left-right-a-b-plank-packs-and-centerline-shift-in-a-flooring-calculator-v0-4-wip</guid><category><![CDATA[algorithms]]></category><category><![CDATA[TypeScript]]></category><category><![CDATA[geometry]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[architecture]]></category><dc:creator><![CDATA[3K Home Warehouse]]></dc:creator><pubDate>Wed, 02 Dec 2026 09:09:53 GMT</pubDate><content:encoded><![CDATA[<p>In our <code>v0.3</code> flooring calculator update, we left one clear open question on the table: <strong>how should an estimation utility model click-lock herringbone flooring</strong>, where every plank lies at 45 degrees to the room walls and boxes ship with paired Left (<code>A</code>) and Right (<code>B</code>) click profiles?</p>
<p>Most online estimators handle herringbone by raising the flat waste multiplier from <code>+7%</code> to <code>+12%</code> or <code>+15%</code>. When we built a small 2D polygon-clipping simulator in TypeScript to test that assumption against real room dimensions, we ran into a physical constraint that flat multipliers miss completely: <strong>A/B pack imbalance caused by starting centerline alignment</strong>.</p>
<h2>Why total plank count is not enough for herringbone</h2>
<p>Unlike straight running-bond planks where any board fits any row, most floating herringbone laminate and engineered products use directional <code>A</code> (left-handed) and <code>B</code> (right-handed) locking tongues. A standard box of <code>600 mm x 100 mm</code> planks (<code>20 planks/box = 1.200 m2/box</code>) contains <strong>10 A-planks and 10 B-planks</strong>.</p>
<p>That means your true minimum box order is governed by the bottleneck side, not the combined plank total:</p>
<pre><code class="language-ts">const boxesByTotal = Math.ceil((netA + netB) / planksPerBox);
const boxesByAB = Math.max(
  Math.ceil(netA / (planksPerBox / 2)),
  Math.ceil(netB / (planksPerBox / 2))
);
</code></pre>
<p>If a room layout consumes <code>300 A</code> planks and <code>251 B</code> planks:</p>
<ul>
<li>Total plank count says <code>Math.ceil(551 / 20) = 28 boxes</code>.</li>
<li>Paired A/B inventory forces <code>Math.ceil(300 / 10) = 30 boxes</code>, leaving nearly 50 unused B-planks sitting in opened cartons.</li>
</ul>
<h2>Exact 2D lattice tiling without overlap</h2>
<p>For a classic herringbone plank whose length is an integer multiple <code>R</code> of its width (<code>600 mm x 100 mm</code> -&gt; <code>R = 6</code>), we can generate an exact, gap-free herringbone lattice in rotated plank space <code>(u, v)</code> where <code>1 grid unit = plankWidthMm</code>:</p>
<ul>
<li>Every <strong><code>A</code> plank</strong> (<code>R x 1</code> in <code>(u, v)</code>) sits at <code>u0 = y + k * 2 * R</code>, <code>v0 = y</code>.</li>
<li>Every <strong><code>B</code> plank</strong> (<code>1 x R</code> in <code>(u, v)</code>) fills the complementary diagonal stripe at <code>u0 = x</code>, <code>v0 = x - k * 2 * R - 2 * R + 1</code>.</li>
</ul>
<p>Each plank rectangle is rotated by 45 degrees into room coordinates <code>(x, y)</code> with a horizontal centerline offset <code>shiftXMm</code>:</p>
<pre><code class="language-ts">const s2 = Math.SQRT1_2;
const toRoom = (u: number, v: number, shiftXMm: number): [number, number] =&gt; [
  (u - v) * s2 + shiftXMm,
  (u + v) * s2,
];
</code></pre>
<p>We then clip each plank polygon against the room interior <code>[0, W - 20] x [0, L - 20]</code> (accounting for 10 mm perimeter expansion gaps) using Sutherland-Hodgman clipping. Any plank whose clipped overlap exceeds <code>500 mm2</code> counts toward <code>A</code> or <code>B</code>. For diagonal perimeter tails that use under <code>45%</code> of a full board, we apply a conservative <code>30%</code> reuse rate across the opposite parallel wall (since a diagonal offcut only fits the opposite edge when its angle and tongue orientation match).</p>
<h2>The surprising finding: shifting the centerline saves a full box</h2>
<p>With <code>600 mm x 100 mm</code> planks (<code>R = 6</code>), one full V-chevron repeats horizontally every <code>2 * R * 100 / sqrt(2) = 848.5 mm</code> (<code>424 mm</code> per A-stripe and <code>424 mm</code> per B-stripe).</p>
<p>When a room width leaves an odd remainder against <code>848.5 mm</code> and you start blindly at <code>shiftXMm = 0</code>, the entire right-hand wall can fall inside a single A-stripe, skewing demand heavily toward A-planks. Sweeping <code>shiftXMm</code> in <code>25 mm</code> increments across one repeat cycle (<code>0</code> to <code>850 mm</code>) immediately balances the wall cuts:</p>
<table>
<thead>
<tr>
<th>Room layout (600 x 100 mm, 20 pcs = 1.2 m2/box)</th>
<th align="right">Net area (m2)</th>
<th align="right">Flat +12% boxes</th>
<th>Unshifted A/B (<code>shift=0</code>)</th>
<th align="right">Unshifted boxes</th>
<th align="right">Optimal shift (mm)</th>
<th>Balanced A/B</th>
<th align="right">v0.4 boxes</th>
<th align="right">Boxes saved</th>
</tr>
</thead>
<tbody><tr>
<td>Narrow Hallway (1.5 m x 6.0 m)</td>
<td align="right">9.00</td>
<td align="right">9</td>
<td>90 A / 88 B</td>
<td align="right">9</td>
<td align="right">325</td>
<td>89 A / 89 B</td>
<td align="right">9</td>
<td align="right">0</td>
</tr>
<tr>
<td>Master Bedroom (3.8 m x 4.6 m)</td>
<td align="right">17.48</td>
<td align="right">17</td>
<td>174 A / 160 B</td>
<td align="right">18</td>
<td align="right">250</td>
<td>163 A / 171 B</td>
<td align="right">18</td>
<td align="right">0</td>
</tr>
<tr>
<td>Living Room (4.5 m x 6.8 m)</td>
<td align="right">30.60</td>
<td align="right">29</td>
<td>300 A / 251 B</td>
<td align="right">30</td>
<td align="right">100</td>
<td>285 A / 285 B</td>
<td align="right">29</td>
<td align="right"><strong>1</strong></td>
</tr>
<tr>
<td>Open Living + Dining (5.2 m x 9.0 m)</td>
<td align="right">46.80</td>
<td align="right">44</td>
<td>441 A / 393 B</td>
<td align="right">45</td>
<td align="right">450</td>
<td>439 A / 438 B</td>
<td align="right">44</td>
<td align="right"><strong>1</strong></td>
</tr>
</tbody></table>
<p>Three practical conclusions come straight out of those verified runs:</p>
<ol>
<li><strong>Centerline alignment is not just visual symmetry.</strong> On the <code>4.5 m x 6.8 m</code> living room, shifting the starting V-axis by <code>100 mm</code> collapses a 49-plank imbalance (<code>300 A / 251 B</code>) into an exact <code>285 A / 285 B</code> split, saving <strong>1 full box</strong>.</li>
<li><strong>Medium bedrooms still beat flat <code>+12%</code> guesses.</strong> On the <code>3.8 m x 4.6 m</code> master bedroom (<code>17.48 m2</code>), even after optimal centerline balancing (<code>163 A / 171 B</code>), real paired-pack math still demands <strong>18 boxes</strong> (<code>21.6 m2</code> purchased), one box higher than the flat <code>+12%</code> estimate (<code>17 boxes</code>).</li>
<li><strong>Separate A and B carton SKUs change the math.</strong> Some manufacturers ship <code>A</code> planks and <code>B</code> planks in separate single-handed boxes rather than mixed <code>10A + 10B</code> boxes. Checking box pack format against real product specs (such as the herringbone specifications catalog at <a href="https://3khome.com/san-go-xuong-ca/">3K Home herringbone flooring</a>) before running the calculation prevents over-ordering the unused side.</li>
</ol>
<h2>Current limitations in <code>v0.4-wip</code></h2>
<ul>
<li><strong>Non-integer aspect ratios</strong>: Real planks like <code>604 mm x 94 mm</code> (<code>L / W = 6.42</code>) shift slightly on each step rather than landing on a strict <code>R = 6</code> lattice; the next revision needs continuous <code>(u, v)</code> step offsets instead of integer grid multiples.</li>
<li><strong>L-shaped multi-zone herringbone</strong>: Running continuous herringbone through an archway from a living room into a hallway couples both rooms to one shared <code>shiftXMm</code> axis, so optimizing both zones jointly is harder than optimizing isolated rectangles.</li>
</ul>
<h2>Open questions</h2>
<ol>
<li>For projects using mixed <code>10A + 10B</code> cartons vs separate <code>A-only</code> and <code>B-only</code> boxes, would you expose a carton-type toggle in the calculator UI or keep the default on mixed boxes to avoid overwhelming homeowners?</li>
<li>When laying herringbone across an L-shaped open floor plan, do installers usually center the primary V-line on the main doorway or optimize around the widest uninterrupted living room wall?</li>
</ol>
]]></content:encoded></item><item><title><![CDATA[Selective Page Cache Invalidation vs. Full-Site Cache Purge When WooCommerce Prices Change]]></title><description><![CDATA[On a WooCommerce catalog with thousands of SKUs and dozens of dynamic price list pages, keeping cached HTML pages in sync with live product prices sounds…]]></description><link>https://kho3khome.hashnode.dev/selective-page-cache-invalidation-vs-full-site-cache-purge-when-woocommerce-prices-change</link><guid isPermaLink="true">https://kho3khome.hashnode.dev/selective-page-cache-invalidation-vs-full-site-cache-purge-when-woocommerce-prices-change</guid><category><![CDATA[woocommerce]]></category><category><![CDATA[WordPress]]></category><category><![CDATA[caching]]></category><category><![CDATA[web performance]]></category><dc:creator><![CDATA[3K Home Warehouse]]></dc:creator><pubDate>Tue, 01 Dec 2026 04:53:59 GMT</pubDate><content:encoded><![CDATA[<p>On a WooCommerce catalog with thousands of SKUs and dozens of dynamic price list pages, keeping cached HTML pages in sync with live product prices sounds trivial until you watch server load during a routine price update.</p>
<p>The quickest hack is hooking <code>woocommerce_update_product</code> and calling a full-site cache purge (<code>rocket_clean_domain()</code> or <code>wp_cache_flush()</code>). On a small 50-page brochure site, nobody notices. On a 6,000-SKU catalog with aggressive cache preloading, a single product edit or taxonomy save wipes every cached category, product, and blog URL on the site, triggering a 5-to-6-hour preload storm that eats CPU and degrades Time to First Byte for real visitors.</p>
<h2>Comparing the two strategies in production</h2>
<table>
<thead>
<tr>
<th>Dimension</th>
<th>Full-site cache purge</th>
<th>Selective page cache invalidation</th>
</tr>
</thead>
<tbody><tr>
<td>Implementation effort</td>
<td>3 lines of code</td>
<td>Small reverse-mapping lookup (<code>product_id -&gt; price_page_ids</code>)</td>
</tr>
<tr>
<td>Server load during bulk price imports</td>
<td>Severe CPU spikes + hours of cache preloading</td>
<td>Flat CPU; only 1–5 affected price pages refresh</td>
</tr>
<tr>
<td>Risk of stale prices on dynamic tables</td>
<td>Low, as long as preload catches up</td>
<td>Low, if every price/spec/term mutation maps cleanly</td>
</tr>
<tr>
<td>Maintenance edge cases</td>
<td>None in code, heavy on ops</td>
<td>Must catch direct DB updates via a lightweight nightly check</td>
</tr>
</tbody></table>
<h2>How we map a changed product back to only the affected price pages</h2>
<p>Each published price list page stores a tiny JSON configuration in post meta listing which WooCommerce product categories it renders. Instead of wiping the entire site cache on product save, we collect dirty product IDs during the PHP request and flush only the matching price pages once at <code>shutdown</code>:</p>
<pre><code class="language-php">&lt;?php
defined( 'ABSPATH' ) || exit;

/**
 * Collect changed product IDs during the request, then purge only
 * the price list pages whose configured categories intersect those products.
 */
function wpdpl_collect_dirty_product( int $product_id ): void {
	static $dirty_ids  = array();
	static $registered = false;

	$dirty_ids[ $product_id ] = true;

	if ( $registered ) {
		return;
	}
	$registered = true;

	add_action( 'shutdown', function () use ( &amp;$dirty_ids ): void {
		if ( empty( $dirty_ids ) ) {
			return;
		}

		$affected_page_ids = wpdpl_find_price_pages_for_products( array_keys( $dirty_ids ) );
		foreach ( $affected_page_ids as $page_id ) {
			wpdpl_purge_single_url( get_permalink( $page_id ) );
		}
	} );
}

/**
 * Purge a single URL in WP Rocket / LiteSpeed / Nginx helper without
 * triggering a full-domain cache wipe.
 */
function wpdpl_purge_single_url( string $url ): void {
	if ( ! $url ) {
		return;
	}

	if ( function_exists( 'rocket_clean_files' ) ) {
		rocket_clean_files( array( $url ) );
	}
	do_action( 'litespeed_purge_url', $url );
}
</code></pre>
<p>Two details save a surprising amount of wasted work when implementing this:</p>
<ol>
<li><strong>Deduplicate inside the request (<code>shutdown</code> flush).</strong> When WooCommerce saves a product, it often updates <code>_price</code>, <code>_regular_price</code>, <code>_sale_price</code>, and terms across five separate hooks within the same request. Collecting IDs in a static map and purging once on <code>shutdown</code> turns five redundant flushes into one.</li>
<li><strong>Watch out for taxonomy-edit purges in caching plugins.</strong> Some page cache plugins automatically trigger a full-site purge whenever a <code>product_cat</code> term is updated via CLI or batch scripts unless you wrap bulk writes with their import flag (for example, <code>rocket_is_importing</code>).</li>
</ol>
<p>We use this selective invalidation flow across more than 40 group and brand-level WooCommerce sheets at <a href="https://3khome.com/bang-gia/">3K Home Price Lists</a>, keeping category and product caches untouched whenever a single brand adjusts pricing.</p>
<h2>Where selective invalidation still needs a safety net</h2>
<p>Direct SQL imports or ERP connectors that write straight to <code>wp_postmeta</code> will bypass WordPress hooks completely. Pairing selective per-page purging with a quiet nightly hash audit catches any stray drift without ever paying the cost of a full-site purge during business hours.</p>
<p>How does your WordPress stack handle cache invalidation when dynamic shortcode pages pull live WooCommerce pricing: per-URL purging, short TTL micro-caching, or fragment/ESI caching?</p>
]]></content:encoded></item><item><title><![CDATA[Why Storing Background Queues in wp_options Fails Under Bulk WooCommerce Imports (and How We Fixed It)]]></title><description><![CDATA[When you maintain auto-generated price list PDFs for a WooCommerce catalog, the first version of the rebuild queue almost always lives inside wp_options. A…]]></description><link>https://kho3khome.hashnode.dev/why-storing-background-queues-in-wp-options-fails-under-bulk-woocommerce-imports-and-how-we-fixed-it</link><guid isPermaLink="true">https://kho3khome.hashnode.dev/why-storing-background-queues-in-wp-options-fails-under-bulk-woocommerce-imports-and-how-we-fixed-it</guid><category><![CDATA[woocommerce]]></category><category><![CDATA[WordPress]]></category><category><![CDATA[PHP]]></category><category><![CDATA[MySQL]]></category><dc:creator><![CDATA[3K Home Warehouse]]></dc:creator><pubDate>Mon, 30 Nov 2026 09:27:24 GMT</pubDate><content:encoded><![CDATA[<p>When you maintain auto-generated price list PDFs for a WooCommerce catalog, the first version of the rebuild queue almost always lives inside <code>wp_options</code>. A product updates, your hook calls <code>get_option('my_pdf_queue')</code>, appends the affected page ID, calls <code>update_option()</code>, and schedules a single WP-Cron event.</p>
<p>That works fine while one editor updates one product at a time. The moment you run a bulk CSV/ERP price import touching 500 SKUs across concurrent PHP-FPM workers, two silent bugs appear:</p>
<ol>
<li><strong>Lost updates from read-modify-write races.</strong> Worker A reads <code>[12]</code>, Worker B reads <code>[12]</code>, Worker A writes <code>[12, 45]</code>, and Worker B overwrites it with <code>[12, 78]</code>. Page <code>45</code> quietly drops out of the queue and keeps serving stale prices in its PDF until someone notices.</li>
<li><strong>Duplicate rebuild storms on no-op hooks.</strong> WooCommerce fires <code>wp_set_object_terms</code> and meta hooks even when a product is re-saved with identical values. Without debouncing and content hashing, a bulk import queues dozens of unnecessary mPDF renders in a row.</li>
</ol>
<h2>Switching to an atomic queue table with debouncing and content hashing</h2>
<p>To eliminate dropped jobs and avoid hammering PHP-FPM during bulk imports, we replaced the <code>wp_options</code> array with three small pieces (<code>wpdpl_</code> prefix for this clean starter pattern):</p>
<h3>1. One row per page in a dedicated table</h3>
<p>Instead of serializing an array into one option row, create a tiny table via <code>dbDelta()</code> with <code>page_id</code> as the primary key and an atomic <code>INSERT ... ON DUPLICATE KEY UPDATE</code> upsert. Concurrent workers can enqueue different pages (or re-enqueue the same page while a render is already running) without overwriting each other.</p>
<pre><code class="language-php">&lt;?php
defined( 'ABSPATH' ) || exit;

function wpdpl_install_queue_table(): void {
	global $wpdb;
	require_once ABSPATH . 'wp-admin/includes/upgrade.php';

	$table   = $wpdb-&gt;prefix . 'wpdpl_pdf_queue';
	$charset = $wpdb-&gt;get_charset_collate();

	dbDelta( "CREATE TABLE {$table} (
		page_id bigint(20) unsigned NOT NULL,
		bump int(10) unsigned NOT NULL DEFAULT 1,
		failures tinyint(3) unsigned NOT NULL DEFAULT 0,
		queued_at datetime NOT NULL,
		PRIMARY KEY (page_id)
	) {$charset};" );
}

/**
 * Enqueue affected price list page IDs atomically.
 * Incrementing `bump` lets the worker detect changes that arrived mid-render.
 */
function wpdpl_enqueue_pages( array $page_ids ): void {
	global $wpdb;
	$table = $wpdb-&gt;prefix . 'wpdpl_pdf_queue';
	$now   = current_time( 'mysql', true );

	foreach ( array_unique( array_map( 'absint', $page_ids ) ) as $page_id ) {
		if ( ! $page_id ) {
			continue;
		}
		$wpdb-&gt;query(
			$wpdb-&gt;prepare(
				"INSERT INTO {$table} (page_id, bump, failures, queued_at)
				 VALUES (%d, 1, 0, %s)
				 ON DUPLICATE KEY UPDATE bump = bump + 1, failures = 0, queued_at = VALUES(queued_at)",
				$page_id,
				$now
			)
		);
	}
}
</code></pre>
<p>Notice the <code>bump</code> counter: before the cron worker starts rendering <code>page_id</code>, it reads <code>bump</code>. When rendering finishes, it executes <code>DELETE FROM wp_wpdpl_pdf_queue WHERE page_id = %d AND bump = %d</code>. If another price update arrived while mPDF was halfway through rendering that page, <code>bump</code> already incremented, so the row survives for one more fresh pass.</p>
<h3>2. Debounce by 5 minutes and skip unchanged content hashes</h3>
<p>During a bulk price update, prices trickle in over several minutes. Scheduling a single debounced cron run (for example, 300 seconds after the first change, guarded by a dedicated lock option) collapses hundreds of product edits into one batch rebuild.</p>
<p>Inside the worker, before invoking mPDF, compute a SHA-256 hash of the normalized table payload (SKUs, active prices, unit specs, thumbnail hashes) and compare it against the last rendered hash saved in post meta. If the hash matches, skip rendering completely and delete the queue row. That single check eliminated every wasted rebuild triggered by WooCommerce's redundant <code>wp_set_object_terms</code> calls.</p>
<h3>3. Nightly hash reconcile as a safety net</h3>
<p>Direct SQL imports, third-party sync scripts, or expired cron locks can still bypass WordPress hooks occasionally. A lightweight nightly task (running at 02:30 local time) hashes every published price page and queues only the pages whose hash drifted from the last built PDF.</p>
<p>We run this exact queue architecture behind the live multi-level WooCommerce price sheets at <a href="https://3khome.com/bang-gia/">3K Home</a> (<code>https://3khome.com/</code>), covering 40+ group and brand price pages without spiking server load during catalog updates.</p>
<h2>Open questions from running this in production</h2>
<p>A couple of architecture trade-offs we still weigh:</p>
<ol>
<li><strong>Dedicated queue table vs. Action Scheduler</strong>: WooCommerce already ships with Action Scheduler, which handles retries and concurrency well. We kept a minimal custom table because we needed exact <code>page_id</code> deduplication (<code>bump</code> semantics) and zero overhead on small sites, though Action Scheduler shines once you need worker observability in wp-admin.</li>
<li><strong>Self-healing stale locks</strong>: If a PHP worker dies mid-render from an unexpected OOM or restart, a naive transient lock can block rebuilds until TTL expiry, so we pair locks with a timestamp threshold that reclaims orphaned runs.</li>
</ol>
<p>For WordPress teams building background document or feed generators tied to WooCommerce updates, do you prefer Action Scheduler, a lightweight custom MySQL queue table, or pushing generation out to an external Redis/Node worker?</p>
]]></content:encoded></item></channel></rss>