Magento2 | PWA | GraphQL

Hides any other shipping methods if free shipping is available - Magento2


In this article, we will check how to hides any other shipping methods if free shipping is available in Magento 2.

Let's start it by creating custom module.

You can find complete module on Github.

Create folder inside app/code/Vmr/ShippingTweaks

Add registration.php file in it:

<?php
/**
 * Copyright ©  All rights reserved.
 * See COPYING.txt for license details.
 */
use Magento\Framework\Component\ComponentRegistrar;
 
ComponentRegistrar::register(ComponentRegistrar::MODULE, 'Vmr_ShippingTweaks', __DIR__);
Add composer.json file in it:
{
    "name": "vmr/module-shippingtweaks",
    "description": "Magento2 Extension that hides any other shipping methods if free shipping is available.",
    "type": "magento2-module",
    "license": "OSL-3.0",
    "authors": [
        {
            "email": "info@mage2gen.com",
            "name": "Mage2Gen"
        },
        {
            "email": "vijaymrami@gmail.com",
            "name": "vijay rami"
        }
    ],
    "minimum-stability": "dev",
    "require": {},
    "autoload": {
        "files": [
            "registration.php"
        ],
        "psr-4": {
            "Vmr\\ShippingTweaks\\": ""
        }
    }
}
Add etc/module.xml file in it:
<?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="Vmr_ShippingTweaks" setup_version="1.0.0"/>
</config>
public function getAllRates() inside vendor/magento/module-shipping/Model/Rate/Result.php file is responsible to fetch all shipping methods.

To change its behaviour, we will use Plugin method and return only free shipping if it is available.

Create di.xml file inside /app/code/Vmr/ShippingTweaks/etc/ folder.
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
     <!-- plugin -->
    <type name="\Magento\Shipping\Model\Rate\Result">
        <plugin name="Vmr_ShippingTweaks" type="Vmr\ShippingTweaks\Plugin\Shipping\Model\Rate\Result"/>
    </type>
</config>

Create Result.php file inside app/code/Vmr/ShippingTweaks/Plugin/Shipping/Model/Rate folder.

<?php

namespace Vmr\ShippingTweaks\Plugin\Shipping\Model\Rate;

use Magento\Quote\Model\Quote\Address\RateResult\Method;
use Magento\Shipping\Model\Rate\Result as Subject;
use Vmr\ShippingTweaks\Helper\Data as ShippingTweaksHelper;

/**
 * Shipping Result Plugin
 */
class Result
{
    /**
     * Helper
     *
     * @var ShippingTweaksHelper
     */
    protected $helper;

    /**
     * Initialize Plugin
     *
     * @param ShippingTweaksHelper $helper
     */
    public function __construct(
        ShippingTweaksHelper $helper
    ) {
        $this->helper = $helper;
    }

    /**
     * Return all Rates in the Result
     *
     * @param Subject $subject
     * @param Method[] $result
     * @return Method[]
     */
    public function afterGetAllRates(Subject $subject, $result)
    {
        if (!$this->helper->isEnabled()) {
            return $result;
        }
        $rates = $this->getAllFreeRates($result);
        return (count($rates) > 0) ? $rates : $result;
    }

    /**
     * Return all free Rates in the Result
     *
     * @param Method[] $result
     * @return Method[]
     */
    public function getAllFreeRates($result)
    {
        $rates = [];
        foreach ($result ?: [] as $rate) {
            if ($rate->getPrice() < 0.0001) {
                $rates[] = $rate;
            }
        }
        return $rates;
    }
}

Create Data.php file inside app/code/Vmr/ShippingTweaks/Helper folder.

<?php

namespace Vmr\ShippingTweaks\Helper;

use Magento\Store\Model\ScopeInterface;
use Magento\Framework\App\Helper\AbstractHelper;

/**
 * Shipping Tweaks Helper
 */
class Data extends AbstractHelper
{
    /**
     * Enabled Config Path
     */
    const XML_CONFIG_ENABLED = 'shipping/behavior/tweaks';

    /**
     * Check Tweaks mode Functionality Should be Enabled
     *
     * @return bool
     */
    public function isEnabled()
    {
        return $this->_getConfig(self::XML_CONFIG_ENABLED);
    }

    /**
     * Retrieve Store Configuration Data
     *
     * @param   string $path
     * @return  string|null
     */
    protected function _getConfig($path)
    {
        return $this->scopeConfig->getValue($path, ScopeInterface::SCOPE_STORE);
    }
}

Now, we will give some options in Stores > Configuration > Shipping Settings

Create system.xml file inside app/code/Vmr/ShippingTweaks/etc/adminhtml folder.

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Config:etc/system_file.xsd">
    <system>
        <section id="shipping">
            <!-- shipping behavior section -->
            <group id="behavior" translate="label" showInDefault="1" showInWebsite="1" showInStore="1" sortOrder="310">
                <label>Behavior of Methods</label>
                <field id="tweaks" translate="label comment" type="select" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1" canRestore="1">
                    <label>Tweaks Mode</label>
                    <comment>Hides any other shipping methods if free shipping is available.</comment>
                    <source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
                </field>
            </group>
        </section>
    </system>
</config>

And to provide default configuration, create config.xml file inside app/code/Vmr/ShippingTweaks/etc folder.

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Store:etc/config.xsd">
    <default>
        <shipping>
            <behavior>
                <tweaks>1</tweaks>
            </behavior>
        </shipping>
    </default>
</config>

Also create optional Uninstall.php file inside Vmr/ShippingTweaks/Setup folder to remove configurations when you un-install the module. 

<?php

namespace Vmr\ShippingTweaks\Setup;

use Magento\Framework\Setup\UninstallInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\SchemaSetupInterface;
use Magento\Config\Model\ResourceModel\Config\Data\CollectionFactory as ConfigCollectionFactory;

/**
 * ShippingTweaks Uninstall
 */
class Uninstall implements UninstallInterface
{
    /**
     * Config Collection Factory
     *
     * @var ConfigCollectionFactory
     */
    protected $configCollectionFactory;

    /**
     * Initialize Setup
     *
     * @param ConfigCollectionFactory $configCollectionFactory
     */
    public function __construct(
        ConfigCollectionFactory $configCollectionFactory
    ) {
        $this->configCollectionFactory = $configCollectionFactory;
    }

    /**
     * Uninstall DB Schema
     *
     * @param SchemaSetupInterface $setup
     * @param ModuleContextInterface $context
     * @return void
     */
    public function uninstall(SchemaSetupInterface $setup, ModuleContextInterface $context)
    {
        $setup->startSetup();
        $this->removeConfig();
        $setup->endSetup();
    }

    /**
     * Remove Config
     *
     * @return void
     */
    protected function removeConfig()
    {
        $path = 'shipping/behavior';
        /** @var \Magento\Config\Model\ResourceModel\Config\Data\Collection $collection */
        $collection = $this->configCollectionFactory->create();
        $collection->addPathFilter($path);
        $collection->walk('delete');
    }
}

After adding above files, please run Magento commands.

php bin/magento set:upg

php bin/magento set:d:c

php bin/magento set:s:d -f en_US

php bin/magento c:c

php bin/magento c:f

Now, you can in Magento admin there is a new option added with name "Behaviour of Methods" is added at Stores > Configuration > Shipping Settings

And infrontend if free shipping is available then no any other paid shipping method will be display.
0 Comments On "Hides any other shipping methods if free shipping is available - Magento2"

Back To Top