Esto se relaciona con una tienda de ropa en línea. Tenemos productos variables configurados con atributos de color y tamaño, por ejemplo, un producto puede tener 2 variaciones; Verde/Cualquier tamaño y Negro/Cualquier tamaño.
Hay una imagen del producto en el color correspondiente para cada variación, pero en este momento la imagen no cambia a menos que se seleccione un color Y un tamaño (soy consciente de que así es como funciona Woo). Nos gustaría hacer que la imagen cambie cuando SOLO se selecciona un color. Me encontré con este código en SO y en otro sitio. Permite que la imagen de variación de un producto cambie cuando solo se selecciona un atributo principal (p. ej., color), en lugar de tener que seleccionar todos los atributos de variación (p. ej., color y tamaño) para que la imagen cambie.
Este código fue escrito para funcionar con un complemento, sin embargo, la persona que lo escribió mencionó cambiar la línea 6 para usar sin complementos. ¿Alguien puede ayudarme a ajustar este código a mi tienda de comercio electrónico? Sé que esto lo puede hacer fácilmente alguien que entienda JS, pero como no soy desarrollador, es muy difícil para mí. ¡Espero que alguien pueda ayudar!
var image_to_show = ''; var variations = JSON.parse($(".variations_form").attr("data-product_variations")); if(variations) { var first_attr = Object.keys(variations[0].attributes)[0]; // when swatch button is clicked $("ul[data-attribute_name='"+first_attr+"'] li").click(function() { var choice = $(this).attr("data-value"); 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[Object.keys(variations[0].attributes)[0]]) { // change featured image image_to_show = variations[i].image_src; found = true; } } } }); // after woo additional images has changed the image, change it again jQuery(".variations_form").on("wc_additional_variation_images_frontend_image_swap_done_callback", function() { if(image_to_show.length) { $(".attachment-shop_single").attr("src", image_to_show).removeAttr("srcset"); } }); }