Display WooCommerce product variation image upon selection from variation dropdown menu

If you ever need to display WooCommerce product variation image, somewhere in single product page, upon selection from variation dropdown menu then use this technique to achieve that objective. This solution can be useful in situation when you use a third party product slider and that product slider doesn’t support the feature to show the corresponding image upon user’s choice from 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 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>

 

Note: If have never overrode 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 the 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 Comments

  • Marco
    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!
  • Kevin Nguyen
    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?
  • harun thuo
    Hi Saafi Just writing to say thankyou for this. really helped me out more life to you!
    • ThemeMates
      Glad it helped you :)

Leave a comment