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

如何用Shopify Liquid模板获取并展示最近10个已售商品?

用Liquid展示Shopify最近10个已售商品的实现方案

Shopify的Liquid模板没有直接获取已售商品列表的内置标签,但可以通过订单数据间接提取最近售出的商品,以下是具体实现步骤和示例代码:

核心思路

通过orders对象获取最近的订单,从每个订单中提取商品项,按需去重后取前10个商品展示。

示例代码

方案1:直接提取最近10个商品项(含重复)

如果允许展示重复购买的同款商品,可直接遍历最近订单的商品:

{% assign recent_orders = shop.orders | limit: 20 %}  <!-- 取足够多的订单确保能拿到10个商品 -->
{% assign sold_items = '' | split: '' %}

{% for order in recent_orders %}
  {% for line_item in order.line_items %}
    {% if sold_items.size < 10 %}
      {% assign sold_items = sold_items | push: line_item %}
    {% endif %}
  {% endfor %}
{% endfor %}

{% if sold_items.size > 0 %}
  <h3>最近售出的商品</h3>
  <ul>
    {% for item in sold_items %}
      <li>
        <a href="{{ item.product.url }}">
          <img src="{{ item.product.featured_image | img_url: 'small' }}" alt="{{ item.product.title }}">
          <span>{{ item.product.title }}</span>
          <span>售出数量: {{ item.quantity }}</span>
        </a>
      </li>
    {% endfor %}
  </ul>
{% else %}
  <p>暂无售出商品</p>
{% endif %}

方案2:去重后展示最近10个不同商品

如果需要避免重复展示同款商品,可通过商品ID去重:

{% assign recent_orders = shop.orders | limit: 20 %}
{% assign sold_product_ids = '' | split: '' %}
{% assign sold_products = '' | split: '' %}

{% for order in recent_orders %}
  {% for line_item in order.line_items %}
    {% unless sold_product_ids contains line_item.product.id %}
      {% assign sold_product_ids = sold_product_ids | push: line_item.product.id %}
      {% assign sold_products = sold_products | push: line_item.product %}
    {% endunless %}
    {% if sold_products.size >= 10 %}
      {% break %}
    {% endif %}
  {% endfor %}
  {% if sold_products.size >= 10 %}
    {% break %}
  {% endfor %}
{% endfor %}

{% if sold_products.size > 0 %}
  <h3>最近售出的商品</h3>
  <ul>
    {% for product in sold_products %}
      <li>
        <a href="{{ product.url }}">
          <img src="{{ product.featured_image | img_url: 'small' }}" alt="{{ product.title }}">
          <span>{{ product.title }}</span>
        </a>
      </li>
    {% endfor %}
  </ul>
{% else %}
  <p>暂无售出商品</p>
{% endif %}

关键说明

  • shop.orders:默认按订单创建时间倒序排列,直接取最近的订单即可。
  • limit:20:设置足够多的订单数量,确保能提取到10个商品(如果部分订单只有1个商品的话)。
  • line_item对象:包含商品的详细信息,如product(关联商品对象)、quantity(售出数量)等。
  • 性能注意:如果店铺订单量极大,过多遍历订单可能影响加载速度,建议限制订单的limit值,或考虑使用Shopify Metafield存储最近售出商品缓存,优化性能。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 18:17:10