Update WooCommerce variable product images when any attribute is selected

This article shows how to update WooCommerce variable product images when a variation attribute is selected, unlike the default WooCommerce behavior of only updating the image when all attributes are selected.

Why update the variation image before all attributes have been selected.

Changing the WooCommerce variable product image to match the currently selected attributes allows visitors to see what they are purchasing during selection, for example if purchasing a t-shirt with a logo and size attributes to be selected, allowing the image display to update the selected logo even if they have not chosen a size.

Update WooCommerce variable product image when a variation attribute is changed

To change variation image for a WooCommerce product when an attribute dropdown is changed can be achieved using events triggered from WooCommerces add-to-cart-variation javascript file, this allows us to inject out code when a dropdown is updated or a variation is selected.

Capture when WooCommerce variations form is updated

Using the ‘wc_variation_form’ trigger we can capture when a user selects or changes an attribute for a variation, when this happens we capture the variationForm as this will be used later in our updateVariationImage function to find matching variations.

The ‘update_variation_values’ event allows the replacement of the default variation image to happen by using a timeout to update the image.

(function ($) {

    var $form;
    var VariationFormObj = false;

    var updateVariationImage = function () {
        // Code to change variation image
    }

    $(document).ready(function () {

        $form = $('form.variations_form');

        if (!$form.length) {
            return;
        }

        $form.on('wc_variation_form', function (event, variationForm) {

            // Capture VariationForm
            VariationFormObj = variationForm;

            updateVariationImage();
        });

        $form.on('update_variation_values', function () {

            // Escape if VariationForm has not been initialized
            if (!VariationFormObj) {
                return;
            }

            // Need a delay to skip the initial reset image when no variation image is set
            window.setTimeout(function () {
                updateVariationImage();
            }, 20);
        });

    });

})(jQuery);

Check to see if variation image should be updated

To find the number of attributes displayed on a variable products you can use the getChosenAttributes function that returns the number of attributes, chosen attributes and a list of currently selected attributes.

If there is more than 1 variation attribute then and not all attributes have been selected then we can get a list of all possible variations via the findMatchingVariations function, filtering this list to only show variations that match the currently selected attributes.

If there is a list of possible variations then we take the first variation and trigger WooCommerce to update the product image using the wc_variations_image_update.

var updateVariationImage = function () {
    // Code to change variation image

    var chosenAttributes = VariationFormObj.getChosenAttributes();
    if (chosenAttributes.count <= 1) {
        return;
    }

    var res = VariationFormObj.findMatchingVariations(VariationFormObj.variationData, chosenAttributes.data);
    if (res.length > 0 && chosenAttributes.chosenCount > 0 && chosenAttributes.chosenCount < chosenAttributes.count) {

        res = res.filter(item => {

            var matched = true;
            for (var attr_name in chosenAttributes.data) {
                if (chosenAttributes.data[attr_name].length > 0 && chosenAttributes.data[attr_name] !== item.attributes[attr_name]) {
                    matched = false;
                }
            }

            return matched;
        });

        if (res.length > 0) {
            VariationFormObj.$form.wc_variations_image_update(res[0]);
        }
    }
}

Stop WooCommerce variations form using AJAX instead of data attribute

In WooCommerce when variable products are created that have many attribute variations, instead of listing all the product variations on the variation form in a data attribute, WooCommerce will instead use AJAX to find matched product variations. We can however increase the threshold so that WooCommerce will always output the variations data attribute using the following code:

function jc_wcvi_ajax_variation_threshold($default, $product)
{
    return PHP_INT_MAX;
}

add_filter('woocommerce_ajax_variation_threshold', 'jc_wcvi_ajax_variation_threshold', 10, 2);

Conclusion

In this article we explored how to trigger a change in variation image using the default WooCommerce product thumbnail when not all variation attributes are selected, this was achieved using the build in WooCommerce javascript events ‘wc_variation_form’ and ‘update_variation_values’ to display the image of the first matched product variation.

This example could be expanded upon to work with large variable products in WooCommerce that have more variations than the specified ajax threshold, this would be achieved by creating an ajax endpoint to return the first matched variation and checking to see if the form has ajax enabled via the useAjax property.

Leave a Reply

Fields marked with an * are required to post a comment