Magento-2 hide other shipping methods when free shipping is available

May 3, 2020 0 Comments

app/code/Yuvraj/FreeShipping/registration.php

<?php
/**
 * Copyright ©  All rights reserved.
 * See COPYING.txt for license details.
 */
use Magento\Framework\Component\ComponentRegistrar;

ComponentRegistrar::register(ComponentRegistrar::MODULE, 'Yuvraj_FreeShipping', __DIR__);

app/code/Yuvraj/FreeShipping/etc/module.xml

<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
	<module name="Yuvraj_FreeShipping" setup_version="1.0.0"/>
</config>

app/code/Yuvraj/FreeShipping/etc/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\Flatrate">
        <plugin name="disable-flatrate" type="Magneto\Yuvraj\Model\Carrier\Flatrate" sortOrder="1" />
    </type>
</config>

app/code/Yuvraj/FreeShipping/Model/Carrier/Flatrate.php

<?php
namespace Yuvraj\FreeShipping\Model\Carrier;

class Flatrate
{

    const XML_PATH_FREE_SHIPPING_SUBTOTAL = "carriers/freeshipping/free_shipping_subtotal";

    /**
     * @var \Magento\Checkout\Model\Session
     */
    protected $_checkoutSession;

    /**
     * @var \Magento\Framework\App\Config\ScopeConfigInterface
     */
    protected $_scopeConfig;

    public function __construct(
        \Magento\Checkout\Model\Session $checkoutSession,
        \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
        \Magento\Store\Model\StoreManagerInterface $storeManager
    ) {
        $this->_storeManager = $storeManager;
        $this->_checkoutSession = $checkoutSession;
        $this->_scopeConfig = $scopeConfig;
    }

    public function afterCollectRates(\Magento\OfflineShipping\Model\Carrier\Flatrate $flatRate, $result)
    {
        $scopeId = $this->_storeManager->getStore()->getId();

        $storeScope = \Magento\Store\Model\ScopeInterface::SCOPE_STORES;

        // Get MOA value from system configuration.
        $freeShippingSubTotal = $this->_scopeConfig->getValue(self::XML_PATH_FREE_SHIPPING_SUBTOTAL, $storeScope, $scopeId);

        // Get cart subtotal from checkout session.
        $baseSubTotal = $this->_checkoutSession->getQuote()->getBaseSubtotal();

        // Validate subtoal should be empty or Zero.
        if(!empty($baseSubTotal) && !empty($freeShippingSubTotal)) {

            if($baseSubTotal >= $freeShippingSubTotal) {
                return false;
            }
        }

        return $result;
    }
}

[smbtoolbar]

Leave A Comment

To Top