Display product variants metafields

7 0 0

In the same way as the product variants SKUs can be displayed, I'd like to display our product variants metafield called "material". It's stored in variant.metafields.specs.material. How can I achieve this?


I was following https://help.shopify.com/en/themes/customization/products/features/show-sku-numbers


{% if variant.metafields.specs.material != blank %}
<p>Material: {{ variant.metafields.specs.material }}</p>
{% endif %}

This displays the metafield. But it's static, not dynamic like the SKU. When you select variant options (sizes and colors) the SKU changes. The "material" does not. Only if you reload the product page with the variant in the URL, only than the metafield data changes.



Here's the code for the SKU that works:


{% if variant.sku != blank and section.settings.display_sku %}
<p class="sku">SKU:  <span itemprop="sku">{{ variant.sku }}</span></p>
{% endif %}


I assume the issue is in the selectCallback function in sections.js.liquid. There I see:


$('.sku span', $product).text(variant.sku);

So by analogy I added:



$('.material span', $product).text(variant.metafields.specs.material);


This broke the functionality of the product page and the variants select elements disappeared.


Any advice or suggestions?







Replies 22 (22)
New Member
2 0 0

I had two different fields I wanted to display - I copied code from an old developer so not sure if this was the best way to do it, but here is my code:

The place where I wanted the metadata fields displayed:

<div id="casecount" class="product-detail">  </div>
<div id="unitprice" class="product-detail">  </div>

Underneath the variant selector (<option> tag) I put this in. I guessed on the formatting to create an array, but it worked as expected:

{% capture 'meta_data_set' %}
{% for variant in product.variants %}
   {{ variant.sku | json }}: { 	"unit_price": {{ variant.metafields.my_fields.unit_price | json }}, 
            					"case_count": {{ variant.metafields.my_fields.case_count | json }}
   {% unless forloop.last %},{% endunless %}
{% endfor %}
{% endcapture %}

 Then in the selectCallback function I used this code:

var metaDataSet = { {{ meta_data_set }} }

$("#unitprice").html('<span>Unit Price: '+ metaDataSet[variant.sku]["unit_price"] +'</span>');   
$("#casecount").html('<span>Case Count: '+ metaDataSet[variant.sku]["case_count"] +'</span>');  


New Member
3 0 0

I am actually having an issue creating an if logic for the product variant metafields

{% if variant.metafields.variant.shade != blank %}
<p>Hex: {{ variant.metafields.variant.shade }}</p>
{% endif %}

14 0 2

Do you think something like that can be put into a custom liquid code inside the theme editor?
I just want to display the content of a variant metafield.