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.
Are you ready to take your business to the next level? Look no further than the latest ...
By SarahF_Shopify Apr 15, 2024We’re keeping the ball rolling to make sure you’re always ahead of the game. So buckle ...
By JasonH Apr 8, 2024Portrait of Stephen positioned next to an image of planet Earth, with the Stephen's World ...
By JasonH Mar 18, 2024