我在 SO 和另一个网站上遇到过这段代码。它允许在仅选择一个主要属性(例如颜色)时更改产品变体图像,而不是必须选择所有变体属性(例如颜色和尺寸)才能更改图像。
这段代码是为使用插件而编写的,但是编写它的人提到更改第 6 行以便在没有插件的情况下使用。我尝试更改data-attribute_name
为 equal attribute_color
,因为它被命名。我已经使用脚本标签调用了这段代码,functions.php
但不确定我还应该做什么。
我怎样才能使这项工作?
var image_to_show = '';
var variations = JSON.parse($(".variations_form").attr("data-product_variations"));
if(variations) {
var first_attr = Object.keys(variations[0].attributes)[0];
// when swatch button is clicked
$("ul[data-attribute_name='"+first_attr+"'] li").click(function() {
var choice = $(this).attr("data-value");
var found = false;
// loop variations JSON
for(const i in variations) {
if(found) continue;
if(variations.hasOwnProperty(i)) {
// if first attribute has the same value as has been selected
if (choice === variations[i].attributes[Object.keys(variations[0].attributes)[0]]) {
// change featured image
image_to_show = variations[i].image_src;
found = true;
}
}
}
});
// after woo additional images has changed the image, change it again
jQuery(".variations_form").on("wc_additional_variation_images_frontend_image_swap_done_callback", function() {
if(image_to_show.length) {
$(".attachment-shop_single").attr("src", image_to_show).removeAttr("srcset");
}
});
}