In WooCommerce, you may encounter a situation where the price of a product does not update dynamically when certain changes are made, such as selecting a different variation or quantity. This can be frustrating for users who expect to see the updated price immediately. To resolve this issue, you can use JavaScript to update the price dynamically based on the selected options.
Here’s an example code snippet that demonstrates how to achieve this functionality:
(function($) {
$(document).ready(function() {
// Update price dynamically when variation is changed
$('form.variations_form').on('woocommerce_variation_select_change', function() {
var price = parseFloat($(this).find('.woocommerce-variation-price .woocommerce-Price-amount').text().replace(/[^0-9.-]+/g, ''));
var quantity = parseInt($(this).find('input[name=quantity]').val());
var totalPrice = price * quantity;
// Update the displayed price
$('.woocommerce-variation-price .woocommerce-Price-amount').text(totalPrice.toFixed(2));
});
// Update price dynamically when quantity is changed
$('form.cart').on('change', 'input[name=quantity]', function() {
var price = parseFloat($(this).closest('.product').find('.woocommerce-Price-amount').text().replace(/[^0-9.-]+/g, ''));
var quantity = parseInt($(this).val());
var totalPrice = price * quantity;
// Update the displayed price
$(this).closest('.product').find('.woocommerce-Price-amount').text(totalPrice.toFixed(2));
});
});
})(jQuery);
This code snippet uses jQuery to listen for changes in the variation selection and quantity input fields. When a variation is changed, it retrieves the price and quantity values, calculates the total price, and updates the displayed price accordingly. Similarly, when the quantity is changed, it performs the same calculations and updates the price.
You can add this code to your theme’s JavaScript file or use a custom plugin to enqueue the script. Remember to wrap the code within the (function($) { ... })(jQuery);
wrapper to ensure compatibility with WordPress and avoid conflicts with other JavaScript libraries.
By implementing this code snippet, you can ensure that the price of your WooCommerce products updates dynamically, providing a better user experience for your customers.
Examples
Example 1: Updating WooCommerce price dynamically using AJAX
This use case demonstrates how to update the price of a WooCommerce product dynamically using AJAX. The code example includes a JavaScript function that sends an AJAX request to the server, which then updates the price based on the selected product options.
(function($) {
$(document).on('change', '.product-option', function() {
var product_id = $(this).data('product-id');
var selected_options = {};
$('.product-option').each(function() {
var option_name = $(this).data('option-name');
var option_value = $(this).val();
selected_options[option_name] = option_value;
});
$.ajax({
url: ajaxurl,
type: 'POST',
data: {
action: 'wpsnippets_update_product_price',
product_id: product_id,
selected_options: selected_options
},
success: function(response) {
$('.product-price').html(response);
}
});
});
})(jQuery);
The JavaScript code listens for changes in the .product-option
elements and collects the selected options into an object. It then sends an AJAX request to the server, passing the selected options and the product ID. On the server side, a custom PHP function wpsnippets_update_product_price()
is hooked to the wp_ajax_wpsnippets_update_product_price
action. This function calculates and returns the updated price, which is then displayed in the .product-price
element.
Example 2: Updating WooCommerce price dynamically using JavaScript
This use case demonstrates how to update the price of a WooCommerce product dynamically using JavaScript. The code example includes a JavaScript function that calculates the updated price based on the selected product options and updates the price element on the page.
(function($) {
$(document).on('change', '.product-option', function() {
var base_price = parseFloat($('.product-price').data('base-price'));
var selected_options = {};
$('.product-option').each(function() {
var option_name = $(this).data('option-name');
var option_value = $(this).val();
selected_options[option_name] = option_value;
});
var updated_price = base_price;
// Calculate the updated price based on selected options
// ...
$('.product-price').html(updated_price.toFixed(2));
});
})(jQuery);
The JavaScript code listens for changes in the .product-option
elements and collects the selected options into an object. It then calculates the updated price based on the selected options and the base price. The updated price is then displayed in the .product-price
element.
Example 3: Updating WooCommerce price dynamically using a custom hook
This use case demonstrates how to update the price of a WooCommerce product dynamically using a custom hook. The code example includes a custom PHP function that hooks into the woocommerce_get_price_html
filter and modifies the price based on the selected product options.
function wpsnippets_update_product_price_html($price, $product) {
if ($product->is_type('variable')) {
$selected_options = array();
foreach ($product->get_variation_attributes() as $attribute => $options) {
$selected_options[$attribute] = isset($_REQUEST['attribute_' . sanitize_title($attribute)]) ? wc_clean(wp_unslash($_REQUEST['attribute_' . sanitize_title($attribute)])) : '';
}
// Calculate the updated price based on selected options
// ...
$price = 'From ' . wc_price($updated_price);
}
return $price;
}
add_filter('woocommerce_get_price_html', 'wpsnippets_update_product_price_html', 10, 2);
The custom PHP function wpsnippets_update_product_price_html()
is hooked into the woocommerce_get_price_html
filter. It retrieves the selected options from the request and calculates the updated price based on those options. The function then modifies the price HTML to display the updated price.