How to Filter Shipping Method in Onepage Checkout

Unlike event "payment_method_is_active" for payment method filtration, we don't have similar event.

Posted on April 4, 2016 in Magento

Introduction

You may want to filter shipping method in onepage checkout for one of the following scenario:

  • Filter shipping method based on Customer Group.

  • Filter shipping method based on Country, State, Zipcode etc

  • Filter shipping method based on products

Whatever may be the reason we still can filter by overriding: Mage_Shipping_Model_Shipping::collectCarrierRates()

Solution

Suppose a new module (Jeff_Shipmentfilter) has already been created. And we will be hiding flat rate shipping for non-logged in customer.

Step 1: Rewrite the shipping model class: Mage_Shipping_Model_Shipping


#app/code/local/Jeff/Shipmentfilter/etc/config.xml
<global>
    .....
    <models>
        <shipping>
           <rewrite>
               <shipping>Jeff_Shipmentfilter_Model_Shipping</shipping>
           </rewrite>
        </shipping>
    </models>
    .....
</global>

Step 2: Override the method: collectCarrierRates()


#app/code/local/Jeff/Shipmentfilter/Model/Shipping.php
<?php
class Jeff_Shipmentfilter_Model_Shipping extends Mage_Shipping_Model_Shipping {
    public function collectCarrierRates($carrierCode, $request) {
        if( ! $this->_checkCarrierAvailability($carrierCode, $request) ) {
             return $this;
        }
        return parent::collectCarrierRates($carrierCode, $request);
    }

    protected function _checkCarrierAvailability($carrierCode, $request) {
        $isLoggedIn = Mage::getSingleton('customer/session')->isLoggedIn();
        if( $isLoggedIn) {
              if($carrierCode == 'flatrate') {
                   return false;
              }
        }
        
       return true;
    }
}


comments powered by Disqus