请求开发Shopify畅销品集合30天时间范围筛选代码
为Shopify畅销品集合设置30天时间范围条件
Shopify默认的自动化畅销品集合没有内置时间范围筛选功能,要实现仅展示过去30天的畅销产品,有两种可行方案:
方案1:前端模板实时过滤(无需修改集合)
通过Liquid代码在集合模板中筛选过去30天内有销量的产品,按销量排序后渲染。
步骤:
- 找到对应集合的模板文件(比如
collections/best-sellers.liquid) - 替换原有产品循环代码为以下内容:
{% comment %} 计算30天前的日期戳 {% endcomment %} {% assign thirty_days_ago = 'now' | date: '%s' | minus: 2592000 | date: '%Y-%m-%d' %} {% comment %} 筛选过去30天有销量的产品,并按销量降序排列 {% endcomment %} {% assign filtered_products = collection.products | where_exp: 'product', 'product.metafields.sales.last_30_days > 0' | sort: 'metafields.sales.last_30_days' | reverse %} {% if filtered_products.size > 0 %} <div class="grid grid--uniform"> {% for product in filtered_products %} {% include 'product-card' %} {% endfor %} </div> {% else %} <p>暂无过去30天的畅销产品</p> {% endif %}
配套设置:
需要给产品添加元字段sales.last_30_days存储过去30天的累计销量,可通过两种方式维护:
- Shopify Flow:创建每日定时工作,自动计算每个产品过去30天的销量并更新元字段(可视化配置,无需代码)
- API脚本批量更新:用Ruby脚本批量计算并写入元字段:
require 'shopify_api' # 替换为你的店铺域名和API令牌 ShopifyAPI::Base.site = ShopifyAPI::Session.new('your-shop.myshopify.com', 'your-api-token').site thirty_days_ago = 30.days.ago ShopifyAPI::Product.find_each do |product| total_sales = 0 product.variants.each do |variant| # 获取变体过去30天销量 sales_report = ShopifyAPI::Report.find(:all, params: { report_type: 'sales_over_time', filters: { variant_id: variant.id, start_date: thirty_days_ago.strftime('%Y-%m-%d'), end_date: Date.today.strftime('%Y-%m-%d') } }).first total_sales += sales_report&.values&.sum { |v| v['sales'] } || 0 end # 更新元字段 product.add_metafield(ShopifyAPI::Metafield.new( namespace: 'sales', key: 'last_30_days', value: total_sales, value_type: 'integer' )) product.save! end
方案2:定时更新自定义集合
创建一个自定义集合,通过API脚本定时将过去30天的畅销产品添加到集合中,适合需要在后台直接管理集合内容的场景。
步骤:
- 在Shopify后台创建一个空的自定义集合,记录其ID
- 编写脚本定时更新集合产品:
require 'shopify_api' ShopifyAPI::Base.site = ShopifyAPI::Session.new('your-shop.myshopify.com', 'your-api-token').site thirty_days_ago = 30.days.ago target_collection_id = 123456789 # 替换为你的自定义集合ID # 获取过去30天销量TOP50的产品(可调整数量) sales_report = ShopifyAPI::Report.find(:all, params: { report_type: 'sales_by_product', filters: { start_date: thirty_days_ago.strftime('%Y-%m-%d'), end_date: Date.today.strftime('%Y-%m-%d') }, sort: 'sales', direction: 'desc', limit: 50 }).first top_product_ids = sales_report&.values&.map { |item| item['product_id'] } || [] # 更新集合产品列表 collection = ShopifyAPI::Collection.find(target_collection_id) collection.product_ids = top_product_ids collection.save!
运行方式:
用定时任务工具(如Cron、Heroku Scheduler)每天运行一次脚本,确保集合内容实时更新。
注意事项:
- 确保API应用拥有
read_products、read_orders、write_collections等必要权限 - 若使用Shopify Flow,可替代API脚本实现无代码的元字段或集合更新
内容的提问来源于stack exchange,提问作者Jumble
相关产品推荐
相关产品推荐

