Liquid, JavaScript, themes, sales channels
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
Solved! Go to the solution
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.
As a business owner, have you ever wondered when your customer's first impression of yo...
By Skye Jun 6, 2023We're excited to announce improvements to the threaded messaging experience in our communi...
By TyW May 31, 2023Thank you to everyone who participated in our AMA with Klaviyo. It was great to see so man...
By Jacqui May 30, 2023