I am trying to have my on-page subtotal for individual WooCommerce products update on a per-quantity basis. I have found a solution that works perfectly for simple products via the following URL: https://medium.com/@xemoro/how-to-display-the-calculated-subtotal-based-on-quantity-in-woocommerce-single-variable-products-24379410a227.
The simple product code is as follows:
add_action( 'woocommerce_after_add_to_cart_button', 'bbloomer_product_price_recalculate' );
function bbloomer_product_price_recalculate() {
global $product;
echo '<div id="subtot" style="display:inline-block;">Total: <span></span></div>';
$price = $product->get_price();
$currency = get_woocommerce_currency_symbol();
wc_enqueue_js( "
$('[name=quantity]').on('input change', function() {
var qty = $(this).val();
var price = '" . esc_js( $price ) . "';
var price_string = (price*qty).toFixed(2);
$('#subtot > span').html('" . esc_js( $currency ) . "'+price_string);
}).change();
" );
}
The above URL also has a solution for variable products, and the code of which is as follows:
add_action( 'woocommerce_after_add_to_cart_button', 'calculate_product_subtotal' );
function calculate_product_subtotal() {
global $product;
if ( $product->is_type( 'variable' ) ) {
$default_attributes = $product->get_default_attributes();
$variation_id = $product->get_matching_variation( $default_attributes );
$variation = wc_get_product( $variation_id );
$price = $variation->get_price();
} else {
$price = $product->get_price();
}
echo '<div id="subtot" style="display:inline-block;">Total: <span></span></div>';
$currency = get_woocommerce_currency_symbol();
wc_enqueue_js( "
jQuery('[name=quantity]').on('input change', function() {
var qty = jQuery(this).val();
var price = '" . esc_js( $price ) . "';
var price_string = (price * qty).toFixed(2);
jQuery('#subtot > span').html('" . esc_js( $currency ) . "' + price_string);
}).change();
" );
}
However, the variable product code gives my website a critical error, which reads as follows:
Deprecated: Function WC_Product::get_matching_variation is deprecated since version 3.0! Use Product data store find_matching_product_variation instead.
When I attempt to update ‘get_matching_variation’ with ‘find_matching_product_variation’, I get another critical error that reads as follows:
Fatal error: Uncaught Error: Call to undefined method WC_Product_Variable::find_matching_product_variation()
Thanks for everyones help.
Ben Stewart is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.