Menu Close

WooCommerce: Switch Image Background On Color Variation Selection

default

You could upload 10 images, one for each color of your variable product… or you could be slightly smarter and simply upload 1 “blank” image, and then when the user selects a color trigger a background color change!

Easier to code than to explain, so let’s take a look at the screenshot below (image must be a PNG with transparent background) and the PHP snippet. This could be a time-saver, enjoy!

The final output: background-color switches to “Red” once the “Red” variation is selected.

PHP Snippet: Switch Featured Image Background Color On Color Variation Select @ Single Product Page

/**
 * @snippet       Switch Image Background @ WooCommerce Single Variable Product
 * @how-to        Get CustomizeWoo.com FREE
 * @author        Rodolfo Melogli
 * @compatible    WooCommerce 4.0
 * @donate $9     https://businessbloomer.com/bloomer-armada/
 */

add_action( 'woocommerce_after_variations_form', 'bbloomer_switch_image_background_variable_colors' );

function bbloomer_switch_image_background_variable_colors() {
	
	wc_enqueue_js( "
	
		$('input.variation_id').change(function(){
			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');
			}
		});
	
	");
	
}
View Source
Posted in WooCommerce Tips