I Only Speak Liquid

Displaying Variant-Specific Information with Metafields

Michael Morgan
|
August 8, 2024

What I’ve been thinking about:

In the competitive world of e-commerce, providing detailed and variant-specific product information can significantly enhance your customers' shopping experience. By default, Shopify doesn't dynamically display variant metafields based on the selected variant. However, with a few tweaks, you can ensure that this information updates automatically as customers choose different options. In this developer guide, we'll walk you through creating variant metafields in Shopify and show you how to dynamically display these metafields using JavaScript.

Step 1: Creating Variant Metafields in Shopify

First, let's create variant metafields for your product variants. Shopify's admin interface makes it easy to manage metafields without any coding knowledge. Follow these steps:

  1. Navigate to Metafields Settings:
    • In your Shopify admin panel, go to Settings > Custom Data > Variants
  2. Add a New Metafield Definition:
    • Click on Add definition.
    • Define the metafield key and namespace (e.g., custom.description for a description metafield).
    • Select the content type (e.g., Single line text, Multi-line text, etc.).
    • In this example, we will use ‘Multi-line text’
    • Click ‘Save’
  3. Assign Metafields to Variants:
    • Go to Products and select the product you want to edit.
    • Scroll down to the Variants section and click on a variant.
    • Add the desired information for each variant in the Metafields section at the bottom.

Step 2: Setting Up Your Shopify Theme

Next, we'll update your Shopify theme to display the metafield based on the selected variant. We'll use a hidden select element to store the metafield values and JavaScript to update the display.

  1. Add the Hidden Select Element:
    • In this example, we are using the Dawn theme, so we will add this element to the product-variant-picker.liquid snippet
  1. Add the Variant Metafield Display Element:
    • There are a couple of ways to go about adding this.
      1. Add the element in the code files where you want it to display
        1. This could be anywhere in the product.liquid snippet or template depending on the theme
      2. Add the element to a custom liquid block or section provided by the theme
        1. Since Dawn has a custom liquid block, we will add the element there

<!-- Metafield display element -->

<div id="variant-metafield">

 {{ product.selected_or_first_available_variant.metafields.custom.description }}

</div>

  1. Locate a printed variant id element
  • In the Dawn theme, this can be found within the product form
  • The reason why we will use this element is because the native Dawn code updates the value attribute with the currently selected variant id. This will make it easy for us to fetch the currently selected variants' ID
  • Note: not all themes are built the same. Some may have an element like this, and some may not. Most themes input the selected variant ID as a parameter in the URL once the variant is changed.

Step 3: Writing the JavaScript

Finally, we'll write a JavaScript snippet to update the displayed metafield when the variant changes.

<script>

 document.addEventListener('DOMContentLoaded', function() {

   // Get the hidden variant ID input

   const variantInput = document.querySelector('.product-form .product-variant-id');

   if (!variantInput) return;

   // Select the variant metafield display element

   const variantMetafieldDisplay = document.getElementById('variant-metafield');

   // Select the hidden variant metafields select element

   const hiddenVariantMetafields = document.getElementById('hidden-variant-metafields');

   const updateMetafieldDisplay = () => {

     const selectedVariantId = variantInput.value;

     const selectedOption = hiddenVariantMetafields.querySelector(`option[value="${selectedVariantId}"]`);

     if (selectedOption) {

       console.log(selectedOption);

       const metafieldValue = selectedOption.getAttribute('data-metafield');

       variantMetafieldDisplay.innerHTML = metafieldValue;

     }

   };

   // Create an observer instance linked to the callback function

   const observer = new MutationObserver(updateMetafieldDisplay);

   // Start observing the target node for configured mutations

   observer.observe(variantInput, { attributes: true, attributeFilter: ['value'] });

   // Initial update on page load

   updateMetafieldDisplay();

 });

</script>

Step 4: Test the functionality

Once you have all the code added, and you have filled out the variant metafield for variants of a product, preview the theme and head to the product. You should see the metafield appear where you placed it in Step 2.2. Go ahead and change the variant. If you see the metafield update every time you change the variant, hooray you did it! If not, go back through each step and make sure everything is linked together.

Putting It All Together

By following these steps, you can create and display variant-specific metafields dynamically in your Shopify store. This approach allows you to provide detailed, variant-specific information to your customers, enhancing their shopping experience and helping them make more informed purchasing decisions. Happy coding!

3 links you can’t miss:

  1. ChatGPT - One of the ultimate ways to accelerate your workflow! With its ability to generate human-like text, assist with coding, and provide instant solutions, ChatGPT is a game-changer for boosting productivity.
  2. Clockify - My go-to time tracker so I can keep track of time for each of my projects. Clockify helps me manage my hours efficiently, ensuring that I stay on schedule and maintain a balanced workload.
  3. Notion - This is an amazing App/Site that I use as my home base. Notion's versatile platform allows me to organize my work seamlessly, combining note-taking, project management, and collaboration tools all in one place.

1 app I like:

Judge.me

I am sure everyone has used or at least heard of this app and for a good reason. Judge.me Reviews is an essential tool for any e-commerce store, allowing users to easily collect and showcase customer reviews, boosting credibility and sales.

7,93
15,86
23,8
31,73
39,66
47,6
55,53
63,46
71,4

What I’ve been thinking about:

In the competitive world of e-commerce, providing detailed and variant-specific product information can significantly enhance your customers' shopping experience. By default, Shopify doesn't dynamically display variant metafields based on the selected variant. However, with a few tweaks, you can ensure that this information updates automatically as customers choose different options. In this developer guide, we'll walk you through creating variant metafields in Shopify and show you how to dynamically display these metafields using JavaScript.

Step 1: Creating Variant Metafields in Shopify

First, let's create variant metafields for your product variants. Shopify's admin interface makes it easy to manage metafields without any coding knowledge. Follow these steps:

  1. Navigate to Metafields Settings:
    • In your Shopify admin panel, go to Settings > Custom Data > Variants
  2. Add a New Metafield Definition:
    • Click on Add definition.
    • Define the metafield key and namespace (e.g., custom.description for a description metafield).
    • Select the content type (e.g., Single line text, Multi-line text, etc.).
    • In this example, we will use ‘Multi-line text’
    • Click ‘Save’
  3. Assign Metafields to Variants:
    • Go to Products and select the product you want to edit.
    • Scroll down to the Variants section and click on a variant.
    • Add the desired information for each variant in the Metafields section at the bottom.

Step 2: Setting Up Your Shopify Theme

Next, we'll update your Shopify theme to display the metafield based on the selected variant. We'll use a hidden select element to store the metafield values and JavaScript to update the display.

  1. Add the Hidden Select Element:
    • In this example, we are using the Dawn theme, so we will add this element to the product-variant-picker.liquid snippet
  1. Add the Variant Metafield Display Element:
    • There are a couple of ways to go about adding this.
      1. Add the element in the code files where you want it to display
        1. This could be anywhere in the product.liquid snippet or template depending on the theme
      2. Add the element to a custom liquid block or section provided by the theme
        1. Since Dawn has a custom liquid block, we will add the element there

<!-- Metafield display element -->

<div id="variant-metafield">

 {{ product.selected_or_first_available_variant.metafields.custom.description }}

</div>

  1. Locate a printed variant id element
  • In the Dawn theme, this can be found within the product form
  • The reason why we will use this element is because the native Dawn code updates the value attribute with the currently selected variant id. This will make it easy for us to fetch the currently selected variants' ID
  • Note: not all themes are built the same. Some may have an element like this, and some may not. Most themes input the selected variant ID as a parameter in the URL once the variant is changed.

Step 3: Writing the JavaScript

Finally, we'll write a JavaScript snippet to update the displayed metafield when the variant changes.

<script>

 document.addEventListener('DOMContentLoaded', function() {

   // Get the hidden variant ID input

   const variantInput = document.querySelector('.product-form .product-variant-id');

   if (!variantInput) return;

   // Select the variant metafield display element

   const variantMetafieldDisplay = document.getElementById('variant-metafield');

   // Select the hidden variant metafields select element

   const hiddenVariantMetafields = document.getElementById('hidden-variant-metafields');

   const updateMetafieldDisplay = () => {

     const selectedVariantId = variantInput.value;

     const selectedOption = hiddenVariantMetafields.querySelector(`option[value="${selectedVariantId}"]`);

     if (selectedOption) {

       console.log(selectedOption);

       const metafieldValue = selectedOption.getAttribute('data-metafield');

       variantMetafieldDisplay.innerHTML = metafieldValue;

     }

   };

   // Create an observer instance linked to the callback function

   const observer = new MutationObserver(updateMetafieldDisplay);

   // Start observing the target node for configured mutations

   observer.observe(variantInput, { attributes: true, attributeFilter: ['value'] });

   // Initial update on page load

   updateMetafieldDisplay();

 });

</script>

Step 4: Test the functionality

Once you have all the code added, and you have filled out the variant metafield for variants of a product, preview the theme and head to the product. You should see the metafield appear where you placed it in Step 2.2. Go ahead and change the variant. If you see the metafield update every time you change the variant, hooray you did it! If not, go back through each step and make sure everything is linked together.

Putting It All Together

By following these steps, you can create and display variant-specific metafields dynamically in your Shopify store. This approach allows you to provide detailed, variant-specific information to your customers, enhancing their shopping experience and helping them make more informed purchasing decisions. Happy coding!

3 links you can’t miss:

  1. ChatGPT - One of the ultimate ways to accelerate your workflow! With its ability to generate human-like text, assist with coding, and provide instant solutions, ChatGPT is a game-changer for boosting productivity.
  2. Clockify - My go-to time tracker so I can keep track of time for each of my projects. Clockify helps me manage my hours efficiently, ensuring that I stay on schedule and maintain a balanced workload.
  3. Notion - This is an amazing App/Site that I use as my home base. Notion's versatile platform allows me to organize my work seamlessly, combining note-taking, project management, and collaboration tools all in one place.

1 app I like:

Judge.me

I am sure everyone has used or at least heard of this app and for a good reason. Judge.me Reviews is an essential tool for any e-commerce store, allowing users to easily collect and showcase customer reviews, boosting credibility and sales.

Talk to an expert
Discuss the project for free
with a Storetasker Expert
From an Expert
Michael Morgan
7,93
15,86
23,8
31,73
39,66
47,6
55,53
63,46
71,4