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

Shopify技术求助:如何获取客户订单中的商品ID

解决获取客户订单中商品ID的问题

嘿,我完全懂你的需求——你要给买过特定商品的用户开放对应页面,但现在的代码只能拿到订单ID,拿不到里面的商品ID,对吧?

你之前的代码{% for order in customer.orders %} {{ order.id }} {% endfor %}遍历的是订单对象,所以输出的是每个订单的ID,而不是订单里包含的商品ID。要拿到商品ID,你需要再深入一层,遍历每个订单里的商品项(也就是订单中的每一行商品)。

基础解决方案:提取所有商品ID

从语法来看你应该用的是类似Shopify Liquid这类模板语言,你可以嵌套循环,先遍历订单,再遍历订单里的line_items(商品项),然后提取商品的ID:

{% for order in customer.orders %}
  {% for line_item in order.line_items %}
    <!-- 这里输出的就是单个商品的ID -->
    {{ line_item.product.id }}
  {% endfor %}
{% endfor %}

进阶:去重商品ID(避免重复购买的商品多次出现)

如果用户多次购买同一个商品,上面的代码会重复输出同一个商品ID。如果你需要一个去重后的商品ID列表,可以用集合来存储:

{% assign purchased_product_ids = '' %}

{% for order in customer.orders %}
  {% for line_item in order.line_items %}
    {% unless purchased_product_ids contains line_item.product.id %}
      {% assign purchased_product_ids = purchased_product_ids | append: line_item.product.id | append: ',' %}
    {% endunless %}
  {% endfor %}
{% endfor %}

<!-- 现在purchased_product_ids是逗号分隔的去重商品ID列表 -->

验证用户权限

拿到商品ID列表后,你就可以判断当前页面对应的商品ID是否在用户的购买列表里,来控制页面访问权限:

{% if purchased_product_ids contains current_page_product.id %}
  <!-- 用户有权限,显示页面内容 -->
  <h1>欢迎访问商品页面</h1>
  <!-- 页面内容 -->
{% else %}
  <!-- 用户无权限,显示提示 -->
  <p>抱歉,你需要购买该商品才能访问此页面</p>
{% endif %}

注意事项

不同的电商系统/模板框架里,订单商品的字段名可能略有不同:

  • 有的系统可能把商品项叫做products而不是line_items
  • 商品ID的字段可能是id或者product_id,需要根据你使用的平台文档调整

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 10:30:26