如何在Liquid中按产品类型获取列表并实现浏览召回邮件关联产品展示
Problem Diagnosis
The original code has two critical issues preventing it from functioning as required:
- Wrong product selection: Uses
abandoned_products.firstto fetch the earliest viewed product instead of the last one you need. - Invalid filtering logic: Liquid's
wherefilter only supports equality checks, sowhere: 'id', '!=', abandoned_product.idcan't exclude the original product from the related list.
Fixed Code
{% assign abandoned_products = abandoned_visit.products_viewed %} {% assign abandoned_product = abandoned_products.last %} {% comment %} Get the most recently viewed product {% endcomment %} {% if abandoned_product %} <!-- Display the abandoned product --> <h2>You were looking at:</h2> <div> <a href="{{ abandoned_product.url }}"> <img src="{{ abandoned_product.featured_image | img_url: 'medium' }}" alt="{{ abandoned_product.title }}"> <p>{{ abandoned_product.title }}</p> </a> <p>{{ abandoned_product.price | money }}</p> </div> <!-- Fetch and display 3 more products from the same product type --> {% assign product_type = abandoned_product.type %} {% if product_type != blank %} {% comment %} Skip if product has no type set {% endcomment %} {% assign related_products = all_products | where: 'product_type', product_type | reject: 'id', abandoned_product.id | limit: 3 %} {% if related_products.size > 0 %} <h2>You might also like:</h2> <div> {% for product in related_products %} <div style="display: inline-block; margin: 10px;"> <a href="{{ product.url }}"> <img src="{{ product.featured_image | img_url: 'medium' }}" alt="{{ product.title }}"> <p>{{ product.title }}</p> </a> <p>{{ product.price | money }}</p> </div> {% endfor %} </div> {% endif %} {% endif %} {% endif %}
Key Fixes Breakdown
- Target last viewed product: Switched
abandoned_products.firsttoabandoned_products.lastto pull the most recent item the user browsed. - Valid product exclusion: Replaced the invalid inequality
wherecheck withreject: 'id', abandoned_product.id—this correctly removes the original product from the related results. - Type existence check: Added
{% if product_type != blank %}to avoid running unnecessary logic if the abandoned product has no type assigned.
内容的提问来源于stack exchange,提问作者dan k
相关产品推荐
相关产品推荐

