With WooCommerce last version, I need to display on product page the weight of the variation chosen in short description and I would like to display the total weight just beside the add to cart button when you choose more than 1 quantity.
For example: I select 4 quantity. Unit weight is 4 kgs. I need to display: "The total weight is 16kgs".
This code works well if the general product has a weight, but it doesn’t works with variations weight:
function woocommerce_total_product_price() {
global $woocommerce, $product;
// let's setup our divs
echo sprintf('<div id="product_total_price" style="margin-bottom:20px;">%s %s</div>', __('Totale Prodotto:','woocommerce'),'<span class="price">' . $product->get_price() . '</span>');
echo sprintf('<div id="product_total_weight" style="margin-bottom:20px;">%s %s</div>', __('Totale Peso:','woocommerce'),'<span class="weight">' . $product->get_weight() . '</span>');
?>
<script>
jQuery(function($) {
var price = <?php echo $product->get_price(); ?>,
currency = '<?php echo get_woocommerce_currency_symbol(); ?>';
var weight = <?php echo $product->get_weight(); ?>;
$('[name=quantity]').change(function() {
if (!(this.value < 1)) {
var product_total = parseFloat(price * this.value);
$('#product_total_price .price').html( currency + product_total.toFixed(2) );
var weight_total = parseFloat(weight * this.value);
$('#product_total_weight .weight').html( weight_total.toFixed(2) + ' kg');
}
});
});
</script>
<?php
}
add_action( 'woocommerce_single_product_summary', 'woocommerce_total_product_price', 31 );
2
Answers
I see a quantity_input.php file in the theme i use, maybe it's here that quantity input is reset.
And i also have a frontend.js file in plugin folder :
jQuery( function ( $ ) {
You can create a javascript object that will contain the necessary values based on the type of product.
The idea is this:
In the previous function I used the variation slugs to determine which option was chosen. This method works only if the variable product has a single select.
Thanks to @LoicTheAztec’s answer you find here:
I figured I could get the value of the chosen variation id from the hidden input with the
variation_id
class.I changed the function by splitting it in two.
The first script adds the content to the product page (under the add to cart form).
The second adds the script in the footer to handle changing values.
So:
The code has been tested and works. Add it to your active theme’s functions.php.