这与一家在线服装店有关。我们设置了具有颜色和尺寸属性的可变产品,例如,产品可能有 2 个变体;绿色/任何尺寸和黑色/任何尺寸。
每种变体都有相应颜色的产品图像,但目前图像不会切换,除非选择颜色和尺寸(我知道这就是 Woo 开箱即用的方式) 。我们希望能够在仅选择一种颜色时切换图像。
这可行吗?如果是这样,我应该查看哪些钩子(Hook)/过滤器/操作?
最佳答案
我们也遇到了这个问题,我设法用 JavaScript 解决了它。此代码假设您正在使用 Variation Swatches For WooCommerce和 WooCommerce Additional Variation Images 。如果您不使用这些插件,那么您需要调整第 6 行的 jQuery 选择器以及将图像应用到页面的方法。它也仅适用于第一个产品选项,例如颜色不是尺寸。
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");
}
});
}
工作原理:当对第一个选项做出选择时,循环遍历 Product_variations JSON 对象并查找具有匹配值的变体。从第一个匹配中获取图像并将其应用到页面上的特色图像。
您需要将图像应用于每个变体才能使其发挥作用。
注意:这并不是 OP 的精确解决方案,但为其他想要实现此目标的人提供了一个可以遵循的方向。
关于php - WooCommerce - 仅选择一个属性时更改产品图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63525264/