Ash
Ash

Reputation: 49

WooCommerce - change product image when only one attribute is selected?

This relates to an online clothing store. We have variable products set up with colour and size attributes, for example a product might have 2 variations; Green/Any Size and Black/Any Size.

There is an image of the product in the corresponding colour for each variation, but at the moment the image doesn't switch unless a colour AND size is selected (I'm aware this is how Woo works out of the box). We would like to make it so that the image switches when JUST a colour is selected.

Is this doable? If so which hooks/filters/actions should I be looking at?

Upvotes: 2

Views: 11570

Answers (1)

Robbie Lewis
Robbie Lewis

Reputation: 2864

We also faced this problem and I managed to solve it with JavaScript. This code assumes that you are using Variation Swatches For WooCommerce and WooCommerce Additional Variation Images. If you are not using these plugins then you'll need to adjust the jQuery selector on line 6 and the method of applying the image to the page. It also applies to the first product option only e.g. Colour not size.

    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");
            }
        });

    }

How it works: when a choice is made on the first option, loop through the product_variations JSON object and find a variation with a matching value. Take the image from the first match and apply it to the featured image on the page.

You will need images applied to every variation for this to work.

NB: This isn't an exact solution for OP but provides a direction for others to follow who want to achieve this.

Upvotes: 3

Related Questions