如何在Shopify集合页面实现变体Metafield值与价格联动展示
在Shopify集合页实现变体选择时展示对应价格与元字段值的功能
下面是一套和产品页逻辑对齐的可行方案,直接套用即可:
1. 确认元字段与变体数据
首先明确你要调用的元字段命名空间和键(比如你产品页用的是custom.size_note),确保每个变体都配置了该元字段的值。Shopify集合页默认会拉取产品的所有变体数据,无需额外请求。
2. 修改集合页产品卡片模板
找到主题中负责集合页产品卡片的文件(通常是collection.liquid、sections/product-card.liquid或Online 2.0架构下的sections/main-collection-product-grid.liquid),在产品标题下方添加变体选择下拉框和展示容器:
{% for product in collection.products %} <div class="product-card"> <h3>{{ product.title }}</h3> <!-- 仅多变体产品显示下拉选择器 --> {% if product.variants.size > 1 %} <select class="variant-picker" data-product-id="{{ product.id }}"> {% for variant in product.variants %} <option value="{{ variant.id }}" data-price="{{ variant.price | money }}" data-meta="{{ variant.metafields.custom.size_note | default: '无额外信息' }}" > {{ variant.title }} </option> {% endfor %} </select> {% endif %} <!-- 价格+元字段展示容器 --> <div class="variant-display"> <span class="variant-price">{{ product.selected_or_first_available_variant.price | money }}</span> {% if product.selected_or_first_available_variant.metafields.custom.size_note %} <span class="variant-meta-text">{{ product.selected_or_first_available_variant.metafields.custom.size_note }}</span> {% endif %} </div> </div> {% endfor %}
⚠️ 替换代码中的custom.size_note为你实际使用的元字段命名空间和键,default值可根据需求调整。
3. 添加入选事件的JS逻辑
在主题的theme.js或模板文件末尾添加以下JS,监听下拉选择事件并实时更新展示内容:
document.addEventListener('DOMContentLoaded', function() { // 获取所有集合页的变体选择器 const variantPickers = document.querySelectorAll('.variant-picker'); variantPickers.forEach(picker => { picker.addEventListener('change', function() { const selectedOpt = this.options[this.selectedIndex]; // 定位当前产品卡片的展示容器 const displayBox = this.closest('.product-card').querySelector('.variant-display'); // 更新价格 displayBox.querySelector('.variant-price').textContent = selectedOpt.dataset.price; // 更新元字段文本 const metaText = displayBox.querySelector('.variant-meta-text'); if (metaText) { metaText.textContent = selectedOpt.dataset.meta; } }); }); });
4. 可选:调整样式适配主题
根据主题视觉风格,添加基础样式优化排版:
.variant-display { margin-top: 6px; display: flex; align-items: center; gap: 10px; font-size: 14px; } .variant-price { font-weight: 600; color: #e63946; /* 替换为你主题的价格颜色 */ } .variant-meta-text { color: #555; }
关键注意事项
- Online 2.0架构主题需找到对应产品卡片section文件修改,而非直接编辑
collection.liquid - 代码已通过
product.variants.size > 1判断,单变体产品不会显示下拉框 - 测试时需验证变体无元字段值的场景,确保
default值正常生效
内容的提问来源于stack exchange,提问作者zahid3d29
相关产品推荐
相关产品推荐

