Skip to content

Instantly share code, notes, and snippets.

@odessy
Created October 23, 2025 18:21
Show Gist options
  • Save odessy/b3094887fca344fa2f5c19d7e144cf64 to your computer and use it in GitHub Desktop.
Save odessy/b3094887fca344fa2f5c19d7e144cf64 to your computer and use it in GitHub Desktop.
Shopify metaobject swatches on product page
let ColorMatch = class ColorMatch {
init() {
...
const newColors = document.querySelector('[data-swatches-json]');
if (newColors && newColors.innerHTML !== '') {
const colors = JSON.parse(newColors.innerHTML);
return Promise.resolve(this.matchColors(colors, this.settings.color));
}
...
}
matchColors(colors, name) {
...
if(value.startsWith('//')){
img = value;
} else {
img = `${path}${encodeURIComponent(value)}`;
}
<script data-swatches-json type="application/json">
{% if product.metafields.custom.trim_color %}
{
"colors": [
{% for color_item in product.metafields.custom.trim_color.value %}
{% if color_item %}
{
{% if color_item.image %}
"{{ color_item.label | downcase }}" : "{{ color_item.image.value | image_url: width: 34 }}"
{% else %}
"{{ color_item.label | downcase }}" : "{{ color_item.color }}"
{% endif %}
}{% unless forloop.last %},{% endunless %}
{% endif %}
{% endfor %}
]
}
{% endif %}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment