Solved

Display product variants metafields

ValTodorov
Tourist
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?

 

Thanks,

Val

 

 

 

Accepted Solution (1)
Mircea_Piturca
Shopify Partner
1547 44 344

This is an accepted solution.

Hi Val,

 

Jason pretty much explain the way to do it.

You need to:

1. Store the variant data in a JavaScript variable.

Can be something like this (not tested):

 

{% capture 'meta_data' %}
{% for variant in product.variants %}
  {{ variant.sku | json }}: {{ variant.metafields.specs.material | json }}
  {% unless forloop.last %},{% endunless %}
{% endfor %}
{% endcapture %}

<script>
  var metaData = { {{ meta_data }} }
</script>

 

2. On selectCallback pull data from that metaData object based on the variant SKU and display it in your page.

selectCallback = function(variant, selector) {
  // ... your default selectCallback code here
  var material = metaData[variant.sku];
}

Hope it makes sense.  

 

 

Finally—Add variant descriptions to your products

View solution in original post

Replies 22 (22)