Bhaveshpp

Professional Magento Developr - Healp eachother to grow

Magento2: Disable flatrate and free shipping for frontend area using around plugin

20 Jun 2021 » magento2

Define plugin in di.xml

    <!-- disable flatrat shipping method on frontend -->
    <type name="Magento\OfflineShipping\Model\Carrier\Flatrate">
        <plugin name="Bhaveshpp_Custom_Plugin_Magento_OfflineShipping_Model_Carrier_Flatrate"
                type="Bhaveshpp\Custom\Plugin\Magento\OfflineShipping\Model\Carrier\Flatrate" 
                sortOrder="10"
                disabled="false"/>
    </type>
    <!-- disable free shipping method on frontend -->
    <type name="Magento\OfflineShipping\Model\Carrier\Freeshipping">
        <plugin name="Bhaveshpp_Custom_Plugin_Magento_OfflineShipping_Model_Carrier_Freeshipping"
                type="Bhaveshpp\Custom\Plugin\Magento\OfflineShipping\Model\Carrier\Freeshipping" 
                sortOrder="10"
                disabled="false"/>
    </type>

Freeshipping around plugin code


<?php
namespace Bhaveshpp\Custom\Plugin\Magento\OfflineShipping\Model\Carrier;
use Magento\OfflineShipping\Model\Carrier\Freeshipping as Subject;
use Magento\Quote\Model\Quote\Address\RateRequest;

class Freeshipping
{

    protected $state;

    public function __construct(
        \Magento\Framework\App\State $state
    ){
        $this->state = $state;
    }

    public function aroundCollectRates(Subject $subject, callable $proceed, RateRequest $request)
    {
        $area = $this->state->getAreaCode();
        if ($area != 'adminhtml') {
            return false;
        }
        return $proceed($request);
    }
}

Flatrate around plugin code


<?php
namespace Bhaveshpp\Custom\Plugin\Magento\OfflineShipping\Model\Carrier;
use Magento\OfflineShipping\Model\Carrier\Flatrate as Subject;
use Magento\Quote\Model\Quote\Address\RateRequest;

class Flatrate
{

    protected $state;

    public function __construct(
        \Magento\Framework\App\State $state
    ){
        $this->state = $state;
    }

    public function aroundCollectRates(Subject $subject, callable $proceed, RateRequest $request)
    {
        $area = $this->state->getAreaCode();
        if ($area != 'adminhtml') {
            return false;
        }
        return $proceed($request);
    }
}

Thank you.