造訪每個購物車商品的變體 Shopify
P粉841870942
P粉841870942 2023-12-29 20:38:18
0
2
551

首先,我總是喜歡發布可運行的範例,但由於這是 js 和 Shopify 上伺服器端渲染液體的混合,我無法獲得運行的範例。

在 Shopify 中,您可以從產品模板存取 product 對象,如下所示 {{ Product }}

購物車物件有一個 items 屬性,它是購物車中所有商品的陣列。購物車中的每個 item 物件與 product 物件不同。 product 物件有一個變體列表,而 cart item 物件沒有。

這樣做的目的是能夠編輯購物車中商品的尺寸。

我的問題是,如何才能獲得所有連結的變體?您必須轉到產品並取得其中所有變體的列表,從變體中取得 product_id

這很棘手的原因是,當您獲得購物車物件的獲取回應時,您會為購物車中的每個 item 獲得一個 product_id 。但除非您位於產品頁面,否則您無法取得產品物件。

只是為了幫助視覺化購物車,如下所示:

{
  items: [
    {
      handle: 'product-handle',
      product_id: 123,
      variant_title: 'product variant'
    }
  ]
}

需要完成的是:

{
  items: [
    {
      handle: 'product-handle',
      product_id: 123,
      /**
       * to get this you need first access to the product object from the product 
       * template. You could convert the product to json with a filter
       * e.g. const product = {{ product | json }} but you don't have the 
       * opportunity to be on the product template each time you edit a cart item
      */
      variants: [
        { color: 'white', size: 's' },
        { color: 'white', size: 'm' }
      ]
    }
  ]
}


#
P粉841870942
P粉841870942

全部回覆(2)
P粉116654495

如果您有產品 ID 或句柄,您可以隨時致電 Shopify 以獲取有關該產品的更多信息,例如分配給該產品的所有變體,以及所有選項。因此,要變更為不同的選項,您需要從購物車中刪除變體 ID,然後新增您想要的不同的 ID。您可以使用 StorefrontAPI 呼叫來取得產品資訊。這通常是商家做您需要做的事情的方式。

P粉547362845

經過一整天的鬥爭,我終於明白了。對於曾經遇到過此問題的其他人,您需要執行類似的操作。

從購物車模板中,cart.liquid

#
const cart = (() => {
  const cart = {{ cart | json }}
  const items = []
  let variants

  {% for item in cart.items %}
    item = {{ item | json }}
    variants = []

    {% for variant in item.product.variants %}
      variant = {{ variant | json }}
      variants.push(variant)
    {% endfor %}

    item.variants = variants
    items.push(item)
  {% endfor %}
  cart.items = items

  return cart
})();

現在,對於購物車中的每個商品屬性,您都有其變體。

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!