What's your biggest current challenge? Have your say in Community Polls along the right column.
Our Partner & Developer boards on the community are moving to a brand new home: the .dev community forums! While you can still access past discussions here, for all your future app and storefront building questions, head over to the new forums.

Re: How can I check whether a product variant contains a specific metafield?

How can I check whether a product variant contains a specific metafield?

kestutisbalt
Shopify Partner
11 0 10

 

I am writing a theme block applicable only to the product template, and I want this block to be visible only for product variants that have a certain metafield. One approach that works for now is to loop through all product variants in Liquid and create a list of variants that have this metafield:

 

{% assign variants_with_metafield = '' | split: ',' %}

{% for variant in product.variants %}
{% if variant.metafields.namespace.key %}
{% assign variants_with_metafield = variants_with_metafield | push: variant %}
{% endif %}
{% endfor %}

However, as Shopify now supports up to 2000 variants per product, this solution is no longer viable because only 100 variants can be iterated this way. An alternative could be to request information about the variant with the AJAX API by tracking variant changes:

<script>
    document.addEventListener('change', function() {
        var url = new URL(document.URL);
        var variantId = url.searchParams.get("variant");
        // Request variant information from API?
    });
</script>

 

But I can't find a way to retrieve metafields for a product variant using the AJAX API. Are there any APIs or other methods I could use to implement this functionality?

Reply 1 (1)

sdservices
Shopify Partner
12 1 1

I am sure the product.variants in liquid will support 2000 variants since on developer preview it can already iterate over 2000 variants using the following

{%for variant in product.variants %}