如何在Shopify中用Liquid为不同客户显示不同Variant价格?
问题描述
我们是B2B公司,正在搭建Shopify站点(负担不起Shopify Plus)。现在需要给两类客户在商品详情页展示不同价格:
- 给带「list1」标签的客户显示Variant 1的价格
- 给带「list2」标签的客户显示Variant 2的价格
已经通过客户标签区分群体,也给商品设置了对应价格的两个Variant,但不想付费使用Wholesale Pricing类应用。尝试了以下代码但没生效,需要帮忙修复:
{% if customer.tags contains "list1" %} {% assign current = product.selected_or_first_available_variant %} {%- assign target_variant = product.variants[0] -%} <div class="no-js-hidden" id="variantPrice-{{ section.id }}" role="status" {{ block.shopify_attributes }}> {%- render 'price', product: product, use_variant: true, show_badges: true, price_class: 'price--large' -%} </div> {% else %} {% assign current = product.selected_or_first_available_variant %} {%- assign target_variant = product.variants[1] -%} <div class="no-js-hidden" id="variantPrice-{{ section.id }}" role="status" {{ block.shopify_attributes }}> {%- render 'price', product: product, use_variant: true, show_badges: true, price_class: 'price--large' -%} </div> {% endif %}
修复方案
你的代码核心问题是:虽然定义了target_variant,但调用price模板片段时,并没有把这个指定的变体传进去,还是用了默认的商品选中/首个可用变体,所以价格不会根据客户标签切换。
修复后的代码如下:
{% comment %} 先初始化目标变体为默认值(未登录/无标签客户显示首个可用变体) {% endcomment %} {% assign target_variant = product.selected_or_first_available_variant %} {% comment %} 根据客户标签切换目标变体 {% endcomment %} {% if customer %} {% if customer.tags contains "list1" %} {% assign target_variant = product.variants[0] %} {% elsif customer.tags contains "list2" %} {% assign target_variant = product.variants[1] %} {% endif %} {% endif %} <div class="no-js-hidden" id="variantPrice-{{ section.id }}" role="status" {{ block.shopify_attributes }}> {%- render 'price', product: product, variant: target_variant, use_variant: true, show_badges: true, price_class: 'price--large' -%} </div>
关键说明:
- 传递指定变体:在
render 'price'时新增variant: target_variant参数,让价格模板使用我们指定的变体价格 - 处理无标签/未登录客户:增加了默认值逻辑,未登录或者没有对应标签的客户会显示商品默认的首个可用变体价格
- 变体索引注意事项:
product.variants[0]和product.variants[1]是按变体创建顺序取的,如果你不确定顺序,建议用变体标题或SKU匹配更可靠,比如:{% for variant in product.variants %} {% if variant.title == "List1 Price" %} {% assign target_variant = variant %} {% endif %} {% endfor %}
内容的提问来源于stack exchange,提问作者DuckJr
相关产品推荐
相关产品推荐

