How to enable WooCommerce Switch Image background on color change?

In e-commerce, you can enable background color switches for your products. So, when one chooses a background color, say, Red, then the background switches to Red. Similar is the case with every other color. In this blog, you will learn about WooCommerce switch image background. So, the background color will change right after you select the color variant. 

To make it work, you could upload one simple blank image. In other words, you need a PNG image with a transparent background.

Let’s see how your page will appear after you apply this function: 

Image showing WooCommerce switch image background on color varient selection

Image showing WooCommerce background color change on yellow color selectionImage showing WooCommerce product image backgroud when no color varient is selected

Understood how our picture will showcase! Let’s see how to code it with the help of PHP snippet. So, use this snippet to save your time.

PHP Snippet: WooCommerce Switch Image Background on Color Variation Select @ Product pages

add_action( 'woocommerce_after_variations_form', 'phpsof_switch_image_background_variable_colors' );
function phpsof_switch_image_background_variable_colors() {
   wc_enqueue_js( "
         if('' != $('input.variation_id').val()) {
            if($('#pa_color').val() =='red'){
               $('.woocommerce-product-gallery figure').css('background-color', 'red');
            } else if($('#pa_color').val() =='yellow'){
               $('.woocommerce-product-gallery figure').css('background-color', 'yellow');
         } else {
            $('.woocommerce-product-gallery figure').css('background-color', 'transparent');

Where do you add this snippet?

So, this is how you activate this snippet named WooCommerce switch image background on color variation select. If one changes the color variant, then the product background will appear in that color variant select. Also, it is easier to activate this function with this code. So, to apply this code, just add this PHP snippet at your child theme function.php file’s bottom. It should be placed before “?>”, if you have it there. Apart from this, CSS goes in your child theme style.css file.

Is this snippet still valid?

So, this way, you can learn about WooCommerce switch image background on different color varient selectI have applied this code on the Storefront theme and WordPress friendly hosting PHP 7.3. Let me know if everything works as expected. Share it further if you find this snippet useful for you and it had saved your time.

Also Read, How to Sync Product Quantities at Cart in WooCommerce?

How to Disable Order Email for Free Orders in WooCommerce?

Important links: WooCommerce –