You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WooCommerce产品添加购物车前按数量显示半米计价总金额

WooCommerce面料产品购物车数量提示代码修复

需求说明

  • 面料按半米计价,1个库存单位代表半米面料
  • 添加购物车按钮上方需显示格式:「添加(X)米面料,总价(Price)」,其中X为数量的一半(如数量3对应1.5米),Price随数量递增(如数量3、单价£7时总价£21)
  • 原代码可计算总价,但数量未修改的初始状态下丢失货币符号

修复后完整代码

add_action( 'woocommerce_before_add_to_cart_quantity', 'qty_front_add_cart' ); 
function qty_front_add_cart() { 
    global $product; 
    $initial_qty = 1;
    $initial_meters = $initial_qty / 2;
    $initial_total = wc_get_price_to_display($product) * $initial_qty;

    // 初始化显示正确格式的文本,包含货币符号
    echo sprintf(
        '<div id="product_total_price" style="margin-bottom:20px;">添加(%s)米面料,总价<span class="price">%s</span></div>',
        number_format($initial_meters, 1), // 保留1位小数,符合面料计量习惯
        wc_price($initial_total) // 使用wc_price自动处理货币符号和格式
    );
    ?>
        <script>
            jQuery(function($){ 
                var price = <?php echo wc_get_price_to_display($product); ?>,
                    currencySymbol = '<?php echo esc_js(get_woocommerce_currency_symbol()); ?>';

                // 定义更新显示的函数
                function updateDisplay(qty) {
                    if (qty < 1) qty = 1;
                    var meters = (qty / 2).toFixed(1);
                    var total = (price * qty).toFixed(2);
                    $('#product_total_price').html(
                        '添加(' + meters + ')米面料,总价<span class="price">' + currencySymbol + total + '</span>'
                    );
                }

                // 监听数量变化(支持实时输入)
                $('[name=quantity]').on('change input', function(){
                    updateDisplay(parseInt($(this).val()));
                });

                // 初始化时触发一次更新,确保状态正确
                updateDisplay(<?php echo $initial_qty; ?>);
            });
        </script>
    <?php 
}

修复关键点

  1. 初始显示修复:使用wc_price()函数输出初始总价,自动包含货币符号和正确的价格格式,解决初始状态无货币符号的问题
  2. 格式匹配需求:调整HTML结构为要求的「添加(X)米面料,总价(Price)」格式,初始计算并显示默认数量对应的米数
  3. 增强监听事件:将change事件改为change input,支持实时输入数量时的动态更新(如键盘输入、上下箭头调整)
  4. 统一更新逻辑:封装updateDisplay函数,确保数量变化和初始状态的显示逻辑一致,避免代码冗余

内容的提问来源于stack exchange,提问作者Josh Wright

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 21:50:01