Skip to content

Instantly share code, notes, and snippets.

@carolineschnapp
Last active February 11, 2022 07:16
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save carolineschnapp/8444587 to your computer and use it in GitHub Desktop.
Save carolineschnapp/8444587 to your computer and use it in GitHub Desktop.
Script that updates images on the cart page to show the correct thumbnail as chosen in the Variant Images app.
{% if cart.item_count > 0 %}
<script>
// Script that updates images on the cart page to show the correct thumbnail as chosen in the Variant Images app.
// This works with any markup.
// This works when using Line Item Properties where several items in the cart form can share the same variant ID.
// Author: Caroline Schnapp.
// Place at the top of your cart.liquid template.
(function($) {
var variantImages = {},
productHandles = [];
{% for item in cart.items %}
productHandles.push('{{ item.product.handle }}');
productHandles = $.unique(productHandles);
if (typeof variantImages[{{ item.id | json }}] === 'undefined') {
variantImages[{{ item.id | json }}] = [];
}
variantImages[{{ item.id | json }}].push({{ forloop.index0 }});
{% endfor %}
jQuery(function($) {
$('form[action="/cart"]').each(function() {
var images = $(this).find('img[src*="/products/"]').hide();
var size = images.first().attr('src').match(/thumb|small|compact|medium|large|grande/)[0] || 'small';
for (var i=0;i<productHandles.length;i++){
$.getJSON("/a/variant-images-1?shop=" + Shopify.shop + "&handle=" + productHandles[i], function(data){
$.each(data, function(variantId, image) {
if (typeof variantImages[variantId] !== 'undefined') {
for (var j=0; j<variantImages[variantId].length;j++) {
var oldURLParts = images.eq(variantImages[variantId][j]).attr('src').split('?');
var suffix = '?' + oldURLParts[1];
var prefix = oldURLParts[0].split('/');
prefix.pop();
prefix = prefix.join('/') + '/';
var filename = image.filename.replace('.', '_' + size + '.');
images.eq(variantImages[variantId][j]).attr('src', prefix + filename + suffix).show();
};
}
});
});
}
});
});
})(jQuery);
</script>
{% endif %}
@franz-see
Copy link

Does this still work?

The ajax

$.getJSON("/a/variant-images-1?shop=" + Shopify.shop + "&handle=" + productHandles[i], ...

return 404 for me.

@hossamhossny
Copy link

hossamhossny commented Feb 11, 2022

I actually managed to change the product featured image shown on cart page with the variant image by editing the code in cart-template.liquid
Search for image: item.product.featured_media.preview_image and replace with image: item.variant.featured_media.preview_image

I am still checking where can I do the same trick on the mini side cart.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment