Shopify Liquid模板获取商品变体HS编码失败求助
Hey there, let's figure out why your HS tariff codes aren't showing up in your invoices. The most common culprit here is how you're referencing the metafield in your Liquid code—let's break this down step by step:
1. 检查元字段的命名空间与键名是否正确
Liquid uses the format metafields.namespace.key to access custom metafields, but your current code treats global_harmonized_system_code as a single value, which is almost certainly the issue.
For example, if you created the metafield with:
- Namespace:
global - Key:
harmonized_system_code
Your corrected code should look like this:
{% for line_item in line_items %} {{ line_item.variant.metafields.global.harmonized_system_code }} {% endfor %}
To confirm your exact namespace and key, head to your Shopify Admin:
- Go to the product variant edit page
- Scroll down to the Metafields section
- Check the "Namespace and key" value (it’ll look something like
global.harmonized_system_code)
2. 确认元字段关联在变体(而非商品)级别
Double-check that the HS code metafield is attached to the variant itself, not the parent product. If you added it to the product level, you’d need to adjust your code to access line_item.product.metafields.namespace.key instead—but since you specified it’s a variant-specific code, make sure it’s stored directly on the variant.
3. 添加调试输出排查问题
If you’re still stuck, add debug code to see exactly what metafields are available on the variant:
{% for line_item in line_items %} <!-- Debug: Print all variant metafields as JSON --> {{ line_item.variant.metafields | json }} <!-- Targeted check for your HS code --> {% if line_item.variant.metafields.global and line_item.variant.metafields.global.harmonized_system_code %} HS Code: {{ line_item.variant.metafields.global.harmonized_system_code }} {% else %} HS Code: Not found for this variant {% endif %} {% endfor %}
This will show you every metafield associated with the variant, so you can confirm if your target field exists and how to reference it correctly.
4. 检查元字段的权限设置
Ensure the metafield has the correct visibility settings—if it’s set to "Private", it won’t be accessible in your storefront or invoice templates. In the Shopify Admin, when editing the metafield, set Visibility to "Storefront" so Liquid can access it.
Once you fix the metafield reference format, your HS codes should start appearing in the invoice as expected.
内容的提问来源于stack exchange,提问作者Jeagr




