
Я реализовал следующий код, который правильно отображает на странице варианты гарантии и скорректированную цену. Однако цена не обновляется правильно при изменении вариаций, что приводит к ошибкам расчета. Вот мой код:
Код: Выделить всё
add_action('woocommerce_single_variation', 'add_custom_options', 5);
function add_custom_options() {
?>
[h4]Great, let's talk about the more details:[/h4]
1. Is it still under warranty?
No, the warranty has expired.
Yes, 1-6 months warranty
Yes, over 6 months warranty
Yes, 1 year warranty & unactivated
jQuery(document).ready(function($) {
var originalPrice;
function getOriginalPrice() {
var priceText = $('.woocommerce-variation-price .woocommerce-Price-amount.amount').first().text();
return parseFloat(priceText.replace(/[^\d.]/g, ''));
}
function updatePrice() {
if (isNaN(originalPrice)) {
originalPrice = getOriginalPrice();
}
var warrantyMultiplier = 1.00;
if ($('input[name="warranty_status"]:checked').val() === 'no') {
warrantyMultiplier = 0.90; // No warranty, deduct 10%
} else if ($('input[name="warranty_status"]:checked').val() === '1-6months') {
warrantyMultiplier = 0.92; // 1-6 months warranty, deduct 8%
} else if ($('input[name="warranty_status"]:checked').val() === 'over6months') {
warrantyMultiplier = 0.95; // Over 6 months warranty, deduct 5%
}
var newPrice = Math.round(originalPrice * warrantyMultiplier);
$('.woocommerce-variation-price .woocommerce-Price-amount.amount').html('$' + newPrice + '');
// Update hidden input to ensure the new price is used when added to the cart
$('#custom_price').val(newPrice);
}
// Clear the selected state of all custom options
function resetCustomOptions() {
$('input[name="warranty_status"]').prop('checked', false);
}
$('form.variations_form').on('woocommerce_variation_has_changed', function() {
resetCustomOptions(); // Reset custom options
originalPrice = getOriginalPrice(); // Get new price each time a variation is switched
updatePrice();
});
$('input[name="warranty_status"]').change(function() {
updatePrice();
});
originalPrice = getOriginalPrice();
updatePrice();
});
Подробнее здесь: [url]https://stackoverflow.com/questions/79140428/custom-field-options-price-update-issue-on-woocommerce-variation-change[/url]