Good evening.
I wrote some code to alter the total weight of some specific articles in my cart (due to a specific request of the courier). Before you ask… no, I cannot modify the single article weight, because I have to calculate a special weight for packaging. Yes, it’s a long story,
My code looks like that (simplified version):
function set_my_weight($weight) {
global $woocommerce;
$cart_items = $woocommerce->cart->get_cart();
$addedWeight = 0;
echo "prev: ". $weight;
foreach($cart_items as $prod => $values):
if(conditions):
$addedWeight += 1.5;
endif;
endforeach;
$weight += $addedWeight;
echo "final: ". $weight;
return $weight;
}
add_filter('woocommerce_cart_contents_weight', 'set_my_weight',10,1);
When I echo the value calling
echo WC()->cart->cart_contents_weight;
all seems working fine, but for some reason the shipping costs do not change.
I’m using “WooCommerce Weight Based Shipping” plugin to manage my shipping costs.
Why the new weight is ignored by the plugin?
Thanks
3
Answers
As WooCommerce Weight Based Shipping is a third party plugin, there is different ways to calculate cost changes based on cart weight.
Here below are 2 ways to alter the cart weight.
1) Alter cart contents total weight:
Code goes in functions.php file of your active child theme (or active theme). Tested and works.
2) Alter cart items weight:
Code goes in functions.php file of your active child theme (or active theme). Tested and works.
Now if WooCommerce Weight Based Shipping plugin get the weight from each product, you will be not able to alter cart weight, so shipping costs.
If you are using this WooCommerce Weight Based Shipping plugin,
@LoicTheAztec answer’s could work if you change the cart data early before
WC()->cart->calculate_shipping()
which is using the hookwoocommerce_checkout_update_order_review
.Source: woocommerce/includes/class-wc-ajax.php
The filter woocommerce_cart_contents_weight is not usable since get_cart_contents_weigh is not used to set the shipping fee. A solution is to modify the weight of each product of the cart.