Skip to content

Instantly share code, notes, and snippets.

@BHare1985
Created July 21, 2022 22:56
Show Gist options
  • Save BHare1985/f9c409c825822b769c06397bfc8b84cc to your computer and use it in GitHub Desktop.
Save BHare1985/f9c409c825822b769c06397bfc8b84cc to your computer and use it in GitHub Desktop.
Wordpress WoodMart Theme: Change product image when only ONE attribute is clicked
/*
A very common scenario is to change clothing images but not require them to pick a size.
This is normally a premium feature of other color swatch plugins!
Here is my attempt at making the <strong>first attribute</strong> automatically change to the variation image even if the
other attributes are not selected. Change the `var nthAttributeToSwitchImage = 1;` if you want something other than the
first attribute to change the image.
Followed the post on https://stackoverflow.com/questions/63525264/woocommerce-change-product-image-when-only-one-attribute-is-selected
although the StackOverflow suggested using the "wc_additional_variation_images_frontend_image_swap_done_callback"
event example doesn't exist with woodmart so I had opted for a simple javascript timeout.
This code isn't perfect, in fact, it's very hacky but I am providing it for free. Please feel free to improve it and post it!
Just add this code to your on document ready section of Theme Settings -> Custom JS section.
Screenshot: https://i.imgur.com/CqkESqd.png
Tested on WordPress 6.0, WooCommerce 6.5, Woomart 28 June 2022
*/
var variations = JSON.parse(jQuery(".variations_form").attr("data-product_variations"));
if (variations) {
var nthAttributeToSwitchImage = 1;
var attributeName = Object.keys(variations[nthAttributeToSwitchImage - 1].attributes)[0];
jQuery("[name=" + attributeName + "]").change(function() {
var attribute_clicked = '';
var choice = jQuery(this).val();
var found = false;
// loop variations JSON
for (const i in variations) {
if (found) continue;
if (variations.hasOwnProperty(i)) {
// if first attribute has the same value as has been selected
if (choice === variations[i].attributes[attributeName]) {
// change featured image
attribute_clicked = variations[i];
found = true;
}
}
}
if (found && attribute_clicked) {
setTimeout(function() {
jQuery(".variations_form").wc_variations_image_update(attribute_clicked);
}, 20);
}
});
}
@mhkhaled2
Copy link

but you solution is not working in my website
what do you mean in discord ID ?

@BinTofajjal
Copy link

what do you mean in discord ID ?

https://discord.com/

Nevermind.

Just check the variation image again and check the attribute setting
image

@mhkhaled2
Copy link

already chacked
discord id: halitaydemir_89649

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment