首页 > 解决方案 > Shopify:修改后购物车中的变体不正确

问题描述

我最近添加了教程中代码的修改版本:

https://help.shopify.com/en/themes/customization/products/variants/hide-variants-that-are-sold-out

我对此进行了修改,以仅显示清仓系列中具有价格(特价)比较的变体。有时,我们的商品仅在销售中具有某些变体,并且我们希望在查看清仓系列时仅显示产品的这些变体。我已经让它几乎工作了。唯一的问题是,当从清仓部分 (/collections/clearance/itemonsale) 查看商品然后添加到购物车时,第一个变体被添加到购物车,而不是在下拉框中选择的一个。这仅在商品第一次添加到购物车时发生。如果有人要返回产品并再次添加它会正常工作。通过类别集合 (/collections/category/itemonsale) 或直接 (/products/itemonsale) 访问产品时,一切正常,因此脚本似乎至少在应该触发的时候触发。任何关于我需要在此处更改以完成这项工作的想法将不胜感激。例子:https://evans-daily-grindb.myshopify.com/collections/clearance

在 product.liquid 中(可能不需要 collection.handle=..... 的第二个实例):

{% if collection.handle == 'clearance' and product.options.size == 1 %}
  <script>
    var product_variants_removed = [
      {%- for variant in product.variants -%}
        {%- unless collection.handle == 'clearance' and variant.compare_at_price > 1 -%}
          '{{ variant.title }}',
        {%- endunless -%}
      {%- endfor -%}
    ];
  </script>
{% endif %}

在 theme.js 中:

$(theme.init);
$( document ).ready(function() {
  if( typeof product_variants_removed != undefined ) {  // was there items to be removed?
    var $addToCartForm = $('form[action="/cart/add"]');
    if (window.MutationObserver && $addToCartForm.length) {
      if (typeof observer === 'object' && typeof observer.disconnect === 'function') {
        observer.disconnect();
      }
      var config = { childList: true, subtree: true };
      var observer = new MutationObserver(function() {
        product_variants_removed.forEach(function(item){
          $('.single-option-selector option').filter(function() { return $(this).text() === item; }).remove();
        });
        observer.disconnect();
      });  
      observer.observe($addToCartForm[0], config);
      $('.single-option-selector').trigger('change');
    }
  }
});

标签: javascripte-commerceshopifyshopify-template

解决方案


推荐阅读