Real example: a customer had bought the following products in the cart:
- product A, weight: 0.2kg, Qty: 2, shipping class : FREE shipping
- product B, weight: 0.6kg, Qty: 3, shipping class: weight based shipping
- product C, weight: 0.8kg, Qty: 1, shipping class: weight based shipping
My client is using a table rate shipping plugin, it can only calculate the shipping cost by using total cart contents weight, in this case it is 3.0kg.
But the real chargeable weight is only 2.6kg...
Had searched around and could not find any function to calculate subtotal of cart items weight for specific shipping class , so have just drafted the following function, but it seems not working. Can someone help to improve this function?
// calculate cart weight for certain shipping class only
if (! function_exists('get_cart_shipping_class_weight')) {
function get_cart_shipping_class_weight() {
$weight = 0;
foreach ( $this->get_cart() as $cart_item_key => $values ) {
if ( $value['data']->get_shipping_class() == 'shipping-from-XX' ) {
if ( $values['data']->has_weight() ) {
$weight += (float) $values['data']->get_weight() * $values['quantity'];
}
}
return apply_filters( 'woocommerce_cart_contents_weight', $weight );
}
}
}
// end of calculate cart weight for certain shipping class
Update (the typo error has been corrected).
To make it work you need to use the dedicated
woocommerce_cart_contents_weight
filter hook in a custom hooked function this way:Code goes in function.php file of your active child theme (or active theme). It should works now.
Thanks @Loic TheAztec, just have to remove the extra "->", perhaps your typo error, then everything works perfectly, the credit shall go to @LoicTheAztec! So the correct code should be as follows: