Output variant images from variant metafields

Hi there,

I’m using Shopify’s new meta field feature for my product variants and I want to change metadata after the user changes the variant.
Currently the variant has the following metafields:

variant_image_1 ----> file
variant_image_2 ----> file
variant_image_3 ----> file

These are going to populate the product image gallery. So after a user selects a green shirt, they will only see the green shirt images etc.

Now when I want to get the metadata with JavaScript I get the following error for the file fields:

error: “json not allowed for this object”

Bildschirmfoto 2021-08-07 um 09.38.20.png

Is there any way to get the file URL for the metadata images?

This is my liquid code:

{% for variant in product.variants %}
{% for metafield in product.variants[forloop.index].metafields.my_fields %}
{% assign image_handle = ‘variant_image_’ | append: forloop.index %}
{% assign image_alt = ‘variant_image_’ | append: forloop.index | append: ‘_alt’ %}
{% if product.selected_or_first_available_variant.metafields.my_fields[image_handle] != blank %}

{{ product.selected_or_first_available_variant.metafields.my_fields[image_alt] | escape }}
{% endif %} {% endfor %} {% endfor %}

Now I want to put the images from the selected variant into my product image slider, but I can’t access any file URL to do so.
Is there any way to access the file URL from variant metadata?

Thank you!

1 Like

Hello! Have you found the solution for that?

We had to go about it differently.

Currently, we are outputting all variant images with liquid, and filtering through them via the variant id. I haven’t found any way to output a file URL after fetching the meta fields, unfortunately.

1 Like

I wonder if this answer from ChatGPT will work?

You can then use JavaScript to change the product image when the customer selects a swatch. Here’s an example of the code you can use:

$(document).on('change', 'input[name="swatch"]', function() {
    var imageUrl = $(this).val();
    $('img.product-image').attr('src', imageUrl);
});

This code will listen for changes to the swatch radio buttons and update the product image with the URL of the selected swatch. Note that you will need to replace “img.product-image” with the actual selector for your product image.

1 Like