The objective is make the main price display by showing both regular (crossed out) and sale prices for variation products. If the user selects a one-time purchase, only the regular price should be displayed. Currently, the sale price for subscriptions only appears in the dropdown menu, while the main price is prominent. Image example below.
There are differing prices based on the count, with a 10% discount applied if the subscription is selected, and no discount if a one-time purchase is chosen.
I've experimented with a js script, but it's buggy, especially when items are added to the cart. While it fulfills the requirements, it exhibits issues when returning to the selection after adding an item to the cart; the quantity number is included, and the sale price displays twice. We don't want that. Is there a suitable hook or filter that could manage this more accurately than relying solely on JavaScript?
jQuery(document).ready(function($) {
var originalPriceHtml = ''; // Variable to store the original price HTML
var subscriptionPriceHtml = ''; // Variable to store the subscription price HTML
// Function to capture the original and subscription prices
function capturePrices() {
originalPriceHtml = $('.woocommerce-Price-amount.amount').first().parent().html(); // Assuming this is the non-subscription price format
var subscriptionPriceElement = $('.wcsatt-options-product-dropdown option:selected');
if (subscriptionPriceElement.length) {
var subscriptionPriceText = subscriptionPriceElement.text();
var priceMatch = subscriptionPriceText.match(/\$(\d+\.\d+)/);
if (priceMatch) {
subscriptionPriceHtml = '<ins>' + priceMatch[0] + '</ins>'; // Assuming this is the subscription price format
}
}
}
// Function to update the price display
function updatePriceDisplay() {
var isSubscription = $('input[name="subscribe-to-action-input"]:checked').val() === 'yes';
var priceContainer = $('.woocommerce-variation-price .price');
if (isSubscription && subscriptionPriceHtml !== '') {
// Subscription option selected, update price with subscription discount
priceContainer.html('<del>' + originalPriceHtml + '</del> ' + subscriptionPriceHtml);
} else {
// One-time purchase selected, revert to original non-subscription price
priceContainer.html(originalPriceHtml);
}
}
// Event handler for subscription type radio buttons
$('input[name="subscribe-to-action-input"]').change(function() {
updatePriceDisplay();
});
// Event handler for changes in quantity or other attributes that may affect the price
$('.quantity input, .single_variation_wrap').change(function() {
capturePrices(); // Recapture prices in case they have changed due to quantity/attribute selection
updatePriceDisplay();
});
// Initial capture of prices and update on page load
$(window).on('load', function() {
capturePrices();
updatePriceDisplay();
});
});