In my case, I need to adding shipping cost of Webshopapps Matrix Rates to cart automatically. If you meet the same requirement , you can follow these steps to make it done:
1/Create a xml file to declare new module: app/etc/modules/Inbusiness_Cart.xml
1 2 3 4 5 6 7 8 9 |
<?xml version="1.0"?> <config> <modules> <Inbusiness_Cart> <active>true</active> <codePool>local</codePool> </Inbusiness_Cart> </modules> </config> |
2/Create app/code/local/Inbusiness/Cart/etc/config.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
<?xml version="1.0"?> <config> <modules> <Inbusiness_Cart> <version>1.1.1</version> </Inbusiness_Cart> </modules> <global> <models> <Inbusiness_Cart> <class>Inbusiness_Cart_Model</class> </Inbusiness_Cart> </models> </global> <frontend> <events> <checkout_cart_save_before> <observers> <inbusiness_set_shipping_observer> <type>singleton</type> <class>Inbusiness_Cart/observer</class> <method>setShipping</method> </inbusiness_set_shipping_observer> </observers> </checkout_cart_save_before> </events> </frontend> </config> |
3/ Create app/code/local/Inbusiness/Cart/Model/Observer.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
<?php class Inbusiness_Cart_Model_Observer { private $_shippingCode = 'matrixrate'; private $_country = 'NO'; public function setShipping($observer) { /*if (Mage::registry('checkout_addShipping')) { Mage::unregister('checkout_addShipping'); return; } Mage::register('checkout_addShipping',true);*/ $event = $observer->getEvent(); $cart = $event->getCart(); $rates = $cart->getQuote()->getShippingAddress()->getAllShippingRates(); $allowed_rates = array(); foreach ($rates as $rate) { array_push($allowed_rates,$rate->getCode()); } if (!in_array($this->_shippingCode,$allowed_rates) && count($allowed_rates) > 0) { $shippingCode = $allowed_rates[0]; $cart->getQuote()->getShippingAddress()->setShippingMethod($shippingCode)->save(); } return; } } ?> |
Resource:
http://excellencemagentoblog.com/magento-shipping-method-dropdown-default-shipping-method-on-cart-page
http://www.danneh.org/2010/08/adding-shipping-costs-to-the-cart-automatically-in-magento/
http://www.nicksays.co.uk/magento-events-cheat-sheet-1-8/
Mage::dispatchEvent(‘checkout_cart_save_before’, array(‘cart’=>$this));