WooCommerce按商品品类及数量显示总价与面料长度功能扩展
解决方案:同时支持半米与1/4米品类的面料购买量计算
你无需复制重复函数(PHP不允许同名函数重复定义),直接修改原有函数即可实现两个品类的适配,以下是调整后的完整代码:
add_action( 'woocommerce_before_add_to_cart_quantity', 'display_product_total_amount_html' ); function display_product_total_amount_html() { global $product; // 检查商品是否属于目标品类 $is_half_metre = has_term( 'half-metre', 'product_cat', $product->get_id() ); $is_quarter_metre = has_term( 'quarter-metre', 'product_cat', $product->get_id() ); // 不属于任一品类则退出 if( !$is_half_metre && !$is_quarter_metre ) return; // 根据品类设置每单位对应的米数 $metres_per_qty = $is_half_metre ? 0.5 : 0.25; $display_price = wc_get_price_to_display($product); $formatted_price = '<span class="price-amount">'. number_format($display_price, 2) . '</span>'; // 输出初始价格文本 $price_string = sprintf( __('Add %s for %s (%s)', 'woocommerce'), '<span class="qty-units">1 unit</span>', '<span class="qty-metres">' . $metres_per_qty . ' metre</span>', str_replace('0.00', $formatted_price, wc_price(0)) ); echo '<div class="total-price_qty" style="margin-bottom:20px;">'.$price_string.'</div>' ?> <script> jQuery(function($){ $('input[name=quantity]').on( 'input change', function(){ const qty = $(this).val(); const metresPerQty = <?php echo $metres_per_qty; ?>; const unitPrice = <?php echo $display_price; ?>; if ( qty != 0 ) { const qtyTxt = qty > 1 ? ' units' : ' unit'; const totalMetres = parseFloat(metresPerQty * qty); // 根据总长度判断单复数(1米及以下用metre,超过用metres) const lengthTxt = totalMetres > 1 ? ' metres' : ' metre'; $('.total-price_qty .qty-units').html( parseInt(qty) + qtyTxt ); $('.total-price_qty .qty-metres').html( totalMetres + lengthTxt ); $('.total-price_qty .price-amount').html( parseFloat(unitPrice * qty).toFixed(2) ); } }); }); </script> <?php }
关键改动说明:
- 品类判断逻辑:新增对
quarter-metre品类的检查,只有商品属于两个目标品类之一时才执行后续逻辑 - 动态米数设置:根据商品所属品类自动切换每单位对应的米数(0.5或0.25)
- 优化单复数判断:将原代码按数量判断长度单复数的逻辑,调整为按总长度判断(更符合语义,比如2个1/4米单位总长度是0.5米,仍显示
metre) - 变量提取:JS中提取
metresPerQty和unitPrice变量,提升代码可读性
这样修改后,半米品类和1/4米品类都会自动显示对应的购买量说明,且数量变化时实时更新单位、长度和总价。
内容的提问来源于stack exchange,提问作者Josh Wright
相关产品推荐
相关产品推荐

