Conversations about creating, managing, and using metafields to store and retrieve custom data for apps and themes.
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?
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 %}