【问题标题】:WooCommerce - change product image when only one attribute is selected?WooCommerce - 仅选择一个属性时更改产品图片?
【发布时间】:2020-12-10 23:34:14
【问题描述】:

这与在线服装店有关。我们设置了带有颜色和尺寸属性的可变产品,例如,一个产品可能有 2 个变体;绿色/任何尺寸和黑色/任何尺寸。

每个变体都有相应颜色的产品图片,但目前图片不会切换,除非选择颜色和尺寸(我知道这就是 Woo 开箱即用的工作方式) .我们想让它在只选择一种颜色时切换图像。

这可行吗?如果是这样,我应该查看哪些钩子/过滤器/操作?

【问题讨论】:

    标签: php wordpress woocommerce plugins customization


    【解决方案1】:

    我们也遇到了这个问题,我设法用 JavaScript 解决了这个问题。此代码假定您使用的是Variation Swatches For WooCommerceWooCommerce 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 的确切解决方案,但为其他想要实现此目标的人提供了一个方向。

    【讨论】:

      【解决方案2】:

      您是否阅读了以下内容: https://docs.woocommerce.com/document/variable-product/#add-variation-image 如果你这样做了(我想是的)阅读这里:https://answers.themler.io/questions/135442/woocommerce-product-variation-image-not-showing 另一个错误:

      我已经解决了这个问题,因为我没有在产品级别设置图像。

      试试这个:https://woocommerce.com/products/variation-swatches-and-photos/#

      【讨论】:

      • 感谢您的回复。我们已经为每个产品变体分配了图像。您链接的文章(第二个链接)中描述的错误特定于 Themlr,我们在这里面临的不是错误,我们想更改默认的 WooCommerce 行为。变体色板和照片将属性选择从下拉列表更改为图像/图标,我们已经在使用另一个插件执行此操作,这与我们试图实现的功能不同。
      • 这个问题找到解决办法了吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-09-13
      • 2015-03-24
      • 2021-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多