Programmatically Change Total Weight in Cart
-
11-12-2020 - |
Question
I need to override the total weight of a customers order programmatically based on various conditions.
I am wanting to change the weight of the whole cart from the real value of 5000 to 957565:
// first echo (to check if the weight is actually saved)
echo $quote->getShippingAddress()->getWeight().'<br />';
if ($x == 'y' && $a < $b)
{
$quote = Mage::getSingleton('checkout/session')->getQuote();
$quote->getShippingAddress()->setWeight(957565);
$quote->save();
// second echo
echo $quote->getShippingAddress()->getWeight();
}
Which outputs each time I visit the cart page/another page:
5000
957565
So the weight does seem to be saved correctly when outputting the second echo but when I reload the page or go to the checkout the weight always reverts back to 5000
Solution
The Quote gets recalculated at various stages during a customer's journey through to a completed order. The weight would get recalculated from the individual items in the quote which is why your changes don't survive a reload.
A possibly better approach would be to adjust the weight of an individual quote item or make sure that your code gets executed at the right time, using the event sales_quote_collect_totals_after
for example.