Last active
February 11, 2022 07:16
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{% 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 %} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 withimage: item.variant.featured_media.preview_image
I am still checking where can I do the same trick on the mini side cart.