Display WooCommerce product variation image upon selection from variation dropdown menu

Display WooCommerce product variation image

If you ever need to display a WooCommerce product variation image, somewhere in a single product page, upon selection from the variation dropdown menu then use this technique to achieve that objective. This solution can be useful in situations when you use a third party product slider and that product slider doesn’t support the feature to show the corresponding image upon the user’s choice from the variations dropdown menu. “Product Gallery Slider for WooCommerce” is one such third party product slider, at the time of writing of this post, which doesn’t show the corresponding image of the selected variation from the dropdown menu.

First of all, make a copy of woocommerce/templates/single-product/add-to-cart/variable.php at woocommerce/single-product/add-to-cart/variable.php and then add the following code in the variations.php file after the variations table:


<div class="product-variation-images">
<div id="product-variation-<?php echo $product_variation['variation_id']; ?>" class="product-variation-image product-variation-<?php echo $product_attribute_name ?>" data-attribute="<?php echo $product_attribute_name ?>">
<img src="<?php echo $product_variation['image_src']; ?>" alt="" />
</div>
</div>

Note: If have never overridden WooCommerce files then read more about it at https://docs.woothemes.com/document/template-structure/.

Now add the following js code to your theme’s javascript file:

// watch out of change event on a specific select element by id
    jQuery(document).on('change', 'select#pa_material', function() {
        var value = "";
        
        // get the option that has been selected
        value += ".product-variation-" + $( "select#pa_material option:selected" ).val();
        
        // Hide all custom_variation divs
        $( '.product-variation-images .product-variation-image').css( 'display', 'none' );
        
        // Display only the variation image which matches the criteria
        $( '.product-variation-images ' + value ).css( 'display', 'block' );
    });

The last thing to do is to hide the variation images by default so add the following CSS rule to your theme’s style.css file:
.product-variation-image {
    display: none;
}

Update all three files on your website and if you followed the steps exactly then you should be able to see the variation image when you choose a variation from the dropdown menu.


4 responses to “Display WooCommerce product variation image upon selection from variation dropdown menu”

  1. Hi!
    Thanks for your amazing solution!
    Do you know how to get the link from the images?
    I mean to make the image variations clickable?

    Thanks!

  2. Thank you for your useful post. I want the different goal. I have color attribute, now when customer clicks on the thumbnail image, the color will be selected instead. How can we achieve it?