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

如何为自定义优惠添加Shopify 'Add to Cart'按钮?

Shopify 动态优惠模块加购功能实现方案

我开发了带有优惠计算的动态产品优惠模块,用户可选择产品变体,现需创建「加入购物车」按钮,将产品名称、用户选中的变体及优惠价传入购物车。但我是Shopify开发新手,尚未理解「加入购物车」功能逻辑,恳请提供帮助。

以下是我的现有代码:

main-product.liquid 代码片段

{% when 'select_variants' %}
  {% assign productPrice = product.price %}
  {% assign priceReduce = 100 | minus: block.settings.percentage_first %}
  {% assign discountAmount = productPrice | times: priceReduce %}
  {% assign baseprice = discountAmount | divided_by: 100 %}
  {% assign secondOffer = baseprice | times: 2 %}
  {% assign secondBase = secondOffer | times: priceReduce %}
  {% assign secondOfferAmount = secondBase | divided_by: 100 %}
  {% assign lastOffer = baseprice | times: 3 %}
  {% assign lastbase = lastOffer | times: priceReduce %}
  {% assign lastOfferAmount = lastbase | divided_by: 100 %}

  <div class="card" style="background-color: {{ block.settings.background_color }};" data-title="{{ block.settings.title_offer_first }}" data-price="{{ baseprice }} {{ shop.currency }}">
    <div class="accordion">
      <div class="offerText">
        <p class="title" style="color: {{ block.settings.title_color }}; background: {{ block.settings.background_color }};"> {{ block.settings.title_offer_first }}</p>
        <p class="rightplace">
          <span class="oldprice"><del> {{ product.price }} {{ shop.currency }} </del></span>
          <span class="newprice" style="color: {{ block.settings.colorprice }};">{{ baseprice }}  {{ shop.currency }}</span>
        </p>
      </div>
      <p class="resume" style="color: {{ block.settings.phrase_color }};"> {{ block.settings.phrase1 }} </p>
    </div>
    <!-- 折叠面板内容 -->
    <div class="panel">
      <div class="selecteds">
        {%- for option in product.options_with_values -%}
          {%- assign option_name = 'option' | append: forloop.index -%}
          {%- if product.variants[0][option_name] -%}
            <div class="select-pair">
              <label for="{{ option_name }}">{{ option.name }}</label>
              <select name="{{ option_name }}" id="{{ option_name }}">
                {%- assign unique_option_values = product.variants | map: option_name | uniq -%}
                {%- for option_value in unique_option_values -%}
                  <option value="{{ option_value }}">{{ option_value }}</option>
                {%- endfor -%}
              </select>
            </div>
          {%- endif -%}
        {%- endfor -%}
      </div>
    </div>
  </div>

Schema 配置代码

{
  "type": "select_variants",
  "name": "variant bundle",
  "settings": [
    {
      "type": "text",
      "label": "优惠标题",
      "id": "title_offer_first",
      "default": "STANDARD OFFER",
      "info": "优惠标题内容。"
    },
    {
      "type": "text",
      "label": "优惠描述1",
      "id": "phrase1",
      "default": "Box of surgical masks (x1)",
      "info": "吸引用户的优惠文案"
    },
    {
      "type": "text",
      "label": "优惠比例1",
      "id": "percentage_first",
      "default": "10",
      "info": "设置第一档优惠的百分比"
    },
    {
      "type": "text",
      "label": "优惠标题2",
      "id": "title_offer_second",
      "default": "MOST POPULAR OFFER",
      "info": "第二档优惠标题。"
    },
    {
      "type": "text",
      "label": "优惠描述2",
      "id": "phrase2",
      "default": "Box of surgical masks (x2)",
      "info": "吸引用户的优惠文案"
    },
    {
      "type": "text",
      "label": "优惠比例2",
      "id": "percentage_second",
      "default": "15",
      "info": "设置第二档优惠的百分比"
    },
    {
      "type": "text",
      "label": "优惠标题3",
      "id": "title_offer_last",
      "default": "BEST DEAL  : UP TO 28% OFF",
      "info": "第三档优惠标题。"
    }
  ]
}

JS 交互代码

<script>
  var cards = document.getElementsByClassName('card');
  var i;

  for (i = 0; i < cards.length; i++) {
    cards[i].addEventListener('click', function () {
      // 点击当前卡片前先关闭其他所有卡片
      for (var j = 0; j < cards.length; j++) {
        var panel = cards[j].querySelector('.panel');
        if (cards[j] !== this) {
          cards[j].classList.remove('active-card');
          panel.style.maxHeight = null;
        }
      }
      this.classList.toggle('active-card');
      var panel = this.querySelector('.panel');
      if (panel.style.maxHeight) {
        panel.style.maxHeight = null;
      } else {
        panel.style.maxHeight = panel.scrollHeight + 'px';
      }
    });

    var selects = cards[i].querySelectorAll('select');
    var j;

    for (j = 0; j < selects.length; j++) {
      selects[j].addEventListener('click', function (event) {
        event.stopPropagation(); // 阻止点击事件冒泡到父级卡片
      });
    }
  }
</script>

加购功能实现步骤

1. 核心逻辑说明

Shopify加购依赖**变体ID(variant_id)和购买数量(quantity)**两个核心参数,通过AJAX请求/cart/add.js完成加购。自定义优惠价需要结合Shopify折扣系统或元字段实现,因为购物车默认读取变体原价。

2. 修改main-product.liquid 添加按钮与变体数据

在折叠面板的选项区后添加「加入购物车」按钮,并输出产品变体的JSON数据供JS匹配:

<!-- 在.panel内的selecteds之后添加 -->
<button class="add-to-cart-btn" data-offer-price="{{ baseprice }}" data-product-title="{{ product.title }}">加入购物车</button>

<!-- 在模板末尾添加变体数据存储脚本 -->
<script>
  const productVariants = {{ product.variants | json }};
</script>

3. 更新JS代码 实现加购逻辑

修改现有JS,添加按钮点击事件处理,匹配选中变体并发起加购请求:

<script>
  var cards = document.getElementsByClassName('card');
  var i;

  for (i = 0; i < cards.length; i++) {
    cards[i].addEventListener('click', function () {
      // 点击当前卡片前先关闭其他所有卡片
      for (var j = 0; j < cards.length; j++) {
        var panel = cards[j].querySelector('.panel');
        if (cards[j] !== this) {
          cards[j].classList.remove('active-card');
          panel.style.maxHeight = null;
        }
      }
      this.classList.toggle('active-card');
      var panel = this.querySelector('.panel');
      if (panel.style.maxHeight) {
        panel.style.maxHeight = null;
      } else {
        panel.style.maxHeight = panel.scrollHeight + 'px';
      }
    });

    var selects = cards[i].querySelectorAll('select');
    var j;

    for (j = 0; j < selects.length; j++) {
      selects[j].addEventListener('click', function (event) {
        event.stopPropagation(); // 阻止点击事件冒泡到父级卡片
      });
    }

    // 监听加购按钮点击
    const addToCartBtn = cards[i].querySelector('.add-to-cart-btn');
    if (addToCartBtn) {
      addToCartBtn.addEventListener('click', function(e) {
        e.stopPropagation();
        const card = this.closest('.card');
        const selects = card.querySelectorAll('select');
        const selectedOptions = [];

        // 收集所有选中的选项值
        selects.forEach(select => {
          selectedOptions.push(select.value);
        });

        // 匹配对应的产品变体
        let matchedVariant = null;
        productVariants.forEach(variant => {
          const variantOptions = variant.options;
          let isMatch = true;
          for (let k = 0; k < selectedOptions.length; k++) {
            if (variantOptions[k] !== selectedOptions[k]) {
              isMatch = false;
              break;
            }
          }
          if (isMatch) {
            matchedVariant = variant;
          }
        });

        if (!matchedVariant) {
          alert('未找到匹配的产品变体,请检查选择');
          return;
        }

        // 准备加购请求参数
        const formData = new FormData();
        formData.append('id', matchedVariant.id);
        formData.append('quantity', 1); // 可根据优惠档位调整数量,比如第二档设为2

        // 发起AJAX加购请求
        fetch('/cart/add.js', {
          method: 'POST',
          body: formData
        })
        .then(response => response.json())
        .then(data => {
          if (data.status === 422) {
            alert(data.message);
          } else {
            alert('已添加到购物车');
            // 可选:触发主题自带的购物车刷新逻辑
            if (typeof Shopify !== 'undefined' && Shopify.Cart) {
              Shopify.Cart.refresh();
            }
          }
        })
        .catch(error => {
          console.error('加购失败:', error);
          alert('加购失败,请重试');
        });
      });
    }
  }
</script>

4. 优惠价生效处理

如果要让购物车显示自定义计算的优惠价,推荐两种方案:

  • 方案一:使用折扣码
    在Shopify后台创建对应百分比的折扣码,加购成功后自动应用:
    // 加购成功后添加以下代码
    fetch('/cart/apply_discount.js', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        discount: 'YOUR_DISCOUNT_CODE' // 替换为你的折扣码
      })
    })
    .then(response => response.json())
    .then(discountData => {
      console.log('折扣已应用:', discountData);
      Shopify.Cart.refresh();
    });
    
  • 方案二:批量购买优惠
    如果优惠是基于购买数量(如买2减15%),直接调整加购的quantity参数,并在后台设置对应的价格规则,Shopify会自动计算优惠价。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 03:45:55