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

如何在Shopify中添加自定义价格计算至商品价格

问题

我需要获取客户提供的两个输入值(宽度Breedte、高度Hoogte),通过以下已编写的JavaScript代码计算得出自定义总价custom-total2,目前公式运行正常。请问如何将该自定义计算价格叠加到Shopify Liquid显示的商品价格中?是否需要在所有显示价格的Liquid文件中进行操作?

<script> 
function calc() {   
    var amount = document.getElementById("amount2").value;  
    var amount = parseInt(amount, 10);  
    var quantity = document.getElementById("quantity2").value;  
    var quantity = parseInt(quantity, 10);  
    var total = amount * quantity / 10000 * 72 / 100 * 40 + 90; 
    document.getElementById("custom-total2").value = total;
} 
</script>

<label for="Breedte">Breedte:
    <input type="" id="amount2" name="properties[Breedte]" placeholder="voer uw breedte in CM" name="amount2" oninput="calc();">
</label>
<label for="Hoogte">Hoogte:
    <input type="" id="quantity2" name="properties[Hoogte]" placeholder="voer uw hoogte in CM" name="quantity2" oninput="calc();">
</label>
<label for="Prijs">Prijs
    <input type="" id="custom-total2" name="custom-total2"> 
</label>
解决方案

一、动态叠加自定义价格到商品显示价格

Shopify商品基础价格通过Liquid变量(如{{ product.price | money }}或{{ variant.price | money }})渲染,需通过JavaScript实时修改价格元素内容:

  1. 定位价格元素:找到页面中显示商品价格的HTML元素,通常带有特定class,比如price-item--regular,假设选择器为.product-price。
  2. 修改calc函数:在现有计算逻辑后,增加价格叠加与更新代码:
    function calc() {   
        var amount = document.getElementById("amount2").value;  
        var amount = parseInt(amount, 10) || 0; // 增加默认值避免NaN
        var quantity = document.getElementById("quantity2").value;  
        var quantity = parseInt(quantity, 10) || 0;
        // 计算自定义总价
        var customTotal = amount * quantity / 10000 * 72 / 100 * 40 + 90; 
        document.getElementById("custom-total2").value = customTotal.toFixed(2); // 保留小数
    
        // 更新商品显示价格
        var priceElement = document.querySelector('.product-price');
        if (priceElement) {
            // 提取基础价格(移除货币符号、千分位等非数字字符)
            var basePriceStr = priceElement.textContent.replace(/[^0-9.]/g, '');
            var basePrice = parseFloat(basePriceStr) || 0;
            var finalTotal = basePrice + customTotal;
            // 按店铺货币格式更新显示(示例用欧元,需根据实际调整)
            priceElement.textContent = '€' + finalTotal.toFixed(2);
        }
    }
    
  3. 初始化触发:页面加载完成后调用calc(),确保初始状态价格正确。

二、无需修改所有显示价格的Liquid文件

  • 核心模板优先:商品价格显示集中在产品详情页(如product.liquid或sections/product-template.liquid)、购物车页(cart.liquid),仅需修改这两类模板。
  • 产品详情页:是用户输入尺寸并实时查看价格的核心页面,必须调整此处的价格显示逻辑。
  • 购物车页:需读取properties[Breedte]和properties[Hoogte],用Liquid或JavaScript重新计算并叠加到商品价格上,保证结算价格一致。
  • 其他页面:如产品列表页通常显示基础价格,无需叠加自定义总价,除非业务有特殊要求。

额外注意事项

  • 货币格式适配:不同地区货币符号、格式不同,提取基础价格时需适配店铺设置。
  • 输入验证:添加输入合法性校验,确保宽度、高度为有效数字,避免计算异常。
  • 结算一致性:前端显示价格需与后台结算价格匹配,建议通过Shopify Functions或cart.js在后端重新计算自定义价格,防止前端篡改。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 03:01:37