Accessing all Variant Metafields in Shopify Liquid

A performant way for accessing variant metafields on product pages without using the storefront API.

Rob Johnson

by Rob Johnson

Oct 10th 2024

Shopify's product.variants object doesn't include metafields by default. This can be a challenge if you need to use variant-specific metafields in your theme's JavaScript. Here's a Liquid code snippet that creates a JavaScript object associating metafield data with variant IDs, making it accessible in your front-end code.

Javascript code

You can place this in your product-variant-options.liquid file.

var variantMetafields = {
  {%- for variant in product.variants -%}
    {{ variant.id }}: {
      metafieldKeyHere: {{ variant.metafields['metafield-namespace-here'].metafield-key-here }}
    },
  {%- endfor -%}
};

With this object now created, you can easily add any additional metafields in the same object by adding another value under the variant.id key.
Example:

var variantMetafields = {
  {%- for variant in product.variants -%}
    {{ variant.id }}: {
      "metafieldKeyHere": {{ variant.metafields['metafield-namespace-here'].metafield-key-here }},
      "anotherMetafieldKey": {{variant.metafields['another-metafield-namespace-here'].another-metafield-key-here }}
    }{% unless forloop.last %},{% endunless %}
  {%- endfor -%}
};

JSON object

You can access the object created above via variantMetafields.

{
  "42907514077346": {
    "metafieldKeyHere": false,
    "anotherMetafieldKey": 123
  },
  "41955230515362": {
    "metafieldKeyHere": true,
    "anotherMetafieldKey": 456
  },
  "41955230482594": {
    "metafieldKeyHere": false,
    "anotherMetafieldKey": 789
  }
}

Accessing the variant metafields data

The below is an example only. You will need to add the target variant ID that you're wanting to grab the data for instead of target_variant_id_here.

variantMetafields[target_variant_id_here].metafieldKeyHere;

Summary

This approach lets you efficiently access variant metafields in your JavaScript, enabling dynamic content updates and other front-end enhancements based on variant-specific metafield data that is configurable in Shopify Admin.