Switch Image Background On Color Variation Selection

woocommerce switch image background color change variable yellow

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 to 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!

woocommerce switch image background color change variable
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
 * @author        PHP - Stackoverflow
 * @compatible    WooCommerce 4.0/

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 to add this snippet?

You can place PHP snippets at the bottom of your child theme functions.php file (before “?>” if you have it). CSS, on the other hand, goes in your child theme style.css file. Make sure you know what you are doing when editing such files – if you need more guidance, please take a look at free video tutorial “Where to Place WooCommerce Customization?”

Does this snippet (still) work?

Please let me know in the comments if everything worked as expected. I would be happy to revise the snippet if you report otherwise (please provide screenshots). I have tested this code with the Storefront theme, the WooCommerce version listed above, and a WordPress-friendly hosting on PHP 7+.

If you think this code saved you time & money, feel free to join 10,000+ WooCommerce Weekly subscribers for blog post updates or 250+ PHP  Stackoverflow supporters for 365 days of WooCommerce benefits. Thank you in advance 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *