Last active
July 12, 2021 10:27
-
-
Save hmouhtar/79c0e0ac138bc0da487f9983d1d042b6 to your computer and use it in GitHub Desktop.
Link price to quantity - WooCommerce for Elementor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
add_action( 'woocommerce_before_add_to_cart_quantity', function(){ | |
global $woocommerce, $product; | |
if ( $product->is_type( 'variable' ) ) { | |
?> | |
<script> | |
jQuery(function ($) { | |
$(document).ready(function () { | |
var price, | |
currency = '<?php echo get_woocommerce_currency_symbol(); ?>'; | |
let observer = new MutationObserver((mutations) => { | |
mutations.forEach((mutation) => { | |
if (!mutation.addedNodes) return | |
for (let i = 0; i < mutation.addedNodes.length; i++) { | |
let node = mutation.addedNodes[i]; | |
// Esperar a que el elemento del precio sea insertado en el DOM. | |
if (jQuery(node).hasClass('woocommerce-variation-price')) { | |
$("[name=quantity]").trigger("change"); | |
} | |
} | |
}) | |
}); | |
$('[name=quantity]').change(function () { | |
if (!(this.value < 1)) { | |
var product_total = parseFloat(price * this.value); | |
$('.variation-info .woocommerce-Price-amount.amount').html(currency + product_total.toFixed(2)); | |
} | |
}); | |
// Actualizar el precio dependiendo de la opción de atributo seleccionada. Reemplazar por nombre de atributo. | |
$('[name=attribute_pa_ciudad]').change(function () { | |
price = JSON.parse(document.getElementsByClassName('variations_form')[0].dataset.product_variations).find(variation => { | |
// Obtener el precio del atributo seleccionado. Reemplazar pa_ciudad por nombre del atributo. | |
return variation.attributes.attribute_pa_ciudad === this.value; | |
}).display_regular_price; | |
$("[name=quantity]").trigger("change"); | |
}); | |
observer.observe(document.body, { | |
childList: true, | |
subtree: true, | |
attributes: false, | |
characterData: false | |
}); | |
// Desencadenar un evento de cambio en el select del atributo para actualizar el precio inicial. | |
$("[name=attribute_pa_ciudad]").trigger("change"); | |
}); | |
}); | |
</script> | |
<?php | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment