Magento2.1.9 Shipping Methods – How to Apply Condition in Checkout Shipping Method

customer-groupmagento2shipping-methods

In magento2 checkout page i'm using free shipping method and i need to hide free shipping method only for non stocking customer group and rest of all customer group i want to display free shipping method.So anyone please guide me in which file i have to put condition.Please check attached image.enter image description here

Best Answer

  1. Create custom module Hello_World
  2. Create plugin and configure in di.xml file, app/code/Hello/World/di.xml
<?xml version="1.0"?>
    <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd"> 
        <type name="Magento\OfflineShipping\Model\Carrier\Freeshipping">
          <plugin name="disable-freeshipping" type="Hello\World\Model\Carrier\Freeshipping" sortOrder="1" />  

        </type>      
 </config>
  1. Create model file app/code/Hello/World/Model/Carrier/Freeshipping.php

    <?php
    
    namespace Hello\World\Model\Carrier;    
    
    class Freeshipping{
    
    protected $_checkoutSession;        
    
    protected $_scopeConfig;
    
    protected $_customerSession;
    
    public function __construct(
        \Magento\Checkout\Model\Session $checkoutSession,
        \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Magento\Customer\Model\Session $customerSession
    ) {
        $this->_storeManager = $storeManager;
        $this->_checkoutSession = $checkoutSession;
        $this->_scopeConfig = $scopeConfig;
        $this->_customerSession = $customerSession;
    }
    
    public function afterCollectRates(\Magento\OfflineShipping\Model\Carrier\Freeshipping $freeshipping, $result)
    {   
        //Magento-2 Log Here
        $writer = new \Zend\Log\Writer\Stream(BP.'/var/log/magento2.log');
        $logger = new \Zend\Log\Logger();
        $logger->addWriter($writer);
        //Customer Group ID Here
        $customerGroupId=$this->_customerSession->getCustomer()->getGroupId();     
        $logger->info("Free shipping has been calling and customerGroupId ".$customerGroupId);              
        //keep your customer group id here
        if($customerGroupId === '1'){
            return false;       
        }        
        return $result;
    }  
    
    }
    
Related Topic