3

In the below code, I am hiding all shipping methods based on postal code 2nd value is 0. In this case, all shipping methods are removing. but I want to remove only free shipping. Can you explain how I can do this?

require(['mage/url', 'jquery','domReady!' ,'jquery/ui'],function(url , $)  {
$("[name='postcode']").live('change',function(){
    postCode = $("[name='postcode']").val();
    // console.log(postCode);
    postCode = postCode.slice(1,2);
    console.log(postCode);

            if(postCode == 0){
                    $('.checkout-shipping-method').hide();
                    message = $('#message').length;
                    if(message == 0){
                        $(.checkout-shipping-address').append("<b id=message><a href=mailto:websales@productioncase.com>Contact </a>&nbsp;Production Case for Rural Shipping<b/>");
                        $("#message").css("color","red");
                        $("#message").show();
                    }
                    else if(message){
                        ("#message").show();
                    }
                }
                else{
                    $('.checkout-shipping-method').show();
                    $("#message").hide();
                }
    });
});
2

You can use a simple plugin:

app/code/MageWorx/DisableFreeShipping/etc/di.xml

<?xml version="1.0"?>
<!--
/**
 * Copyright © 2018 MageWorx. All rights reserved.
 * See LICENSE.txt for license details.
 */
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <!-- PLUGINS: -->
    <type name="Magento\OfflineShipping\Model\Carrier\Freeshipping">
        <plugin name="mageworx_disable_free_shipping_by_postcode"
                type="MageWorx\DisableFreeShipping\Plugin\DisableFreeShippingByPostCode"
                sortOrder="20"/>
    </type>
</config>

app/code/MageWorx/DisableFreeShipping/Plugin/DisableFreeShippingByPostCode.php

<?php
/**
 * Copyright © 2020 MageWorx. All rights reserved.
 * See LICENSE.txt for license details.
 */

namespace MageWorx\DisableFreeShipping\Plugin;

/**
 * Class DisableFreeShippingByPostCode
 */
class DisableFreeShippingByPostCode
{
    /**
     * @param \Magento\OfflineShipping\Model\Carrier\Freeshipping $subject
     * @param callable $proceed
     * @param \Magento\Quote\Model\Quote\Address\RateRequest $request
     * @return \Magento\Shipping\Model\Rate\Result|bool
     */
    public function aroundCollectRates(
        \Magento\OfflineShipping\Model\Carrier\Freeshipping $subject,
        callable $proceed,
        \Magento\Quote\Model\Quote\Address\RateRequest $request
    ) {
        if ($request->getDestPostcode()) { // Check is postcode exists in request
            if ($this->postCodeContainsNullOnSecondPosition($request->getDestPostcode())) { // Check is second symbol == 0
                return false; // Disable method
            }
        }

        return $proceed($request);
    }

    /**
     * Test postcode
     *
     * @param string $postCode
     * @return bool
     */
    private function postCodeContainsNullOnSecondPosition(string $postCode): bool
    {
        return stripos($postCode, '0') === 1;
    }
}

Result with 0 in zip on second position and without:

with 0 in zip on second position without 0 in zip

You can add any condition for the freeshipping method in that plugin.

PS: here is complete working code in example module on github.

1

According to your question you need to hide free shipping method if 2nd value of postcode is 0, you can achieve it using below.

app/code/VENDOR/MODULE/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">
    <preference for="Magento\OfflineShipping\Model\Carrier\Freeshipping" type="VENDOR\MODULE\Model\Carrier\Freeshipping" />
</config>

app/code/VENDOR/MODULE/Model/Carrier/Freeshipping.php

<?php

namespace VENDOR\MODULE\Model\Carrier;

use Magento\Quote\Model\Quote\Address\RateRequest;

class Freeshipping extends \Magento\OfflineShipping\Model\Carrier\Freeshipping
{
    public function collectRates(RateRequest $request)
    {
        if (!$this->getConfigFlag('active')) {
            return false;
        }

        $postCode = $request->getDestPostcode();
        $postCode = substr($postCode, 1, 2);

        if($postCode == 0)
        {
            return false;

            // you can use this for custom error message.
            // $error = $this->_rateErrorFactory->create();
            // $error->setCarrier($this->_code);
            // $error->setCarrierTitle($this->getConfigData('title'));
            // $error->setErrorMessage(__('Your Error Message'));
            // return $error;
        }

        /** @var \Magento\Shipping\Model\Rate\Result $result */
        $result = $this->_rateResultFactory->create();

        $this->_updateFreeMethodQuote($request);

        if ($request->getFreeShipping() || $request->getPackageValueWithDiscount() >= $this->getConfigData(
            'free_shipping_subtotal'
        )
        ) {
            /** @var \Magento\Quote\Model\Quote\Address\RateResult\Method $method */
            $method = $this->_rateMethodFactory->create();

            $method->setCarrier('freeshipping');
            $method->setCarrierTitle($this->getConfigData('title'));

            $method->setMethod('freeshipping');
            $method->setMethodTitle($this->getConfigData('name'));

            $method->setPrice('0.00');
            $method->setCost('0.00');

            $result->append($method);
        } elseif ($this->getConfigData('showmethod')) {
            $error = $this->_rateErrorFactory->create();
            $error->setCarrier($this->_code);
            $error->setCarrierTitle($this->getConfigData('title'));
            $errorMsg = $this->getConfigData('specificerrmsg');
            $error->setErrorMessage(
                $errorMsg ? $errorMsg : __(
                    'Sorry, but we can\'t deliver to the destination country with this shipping module.'
                )
            );
            return $error;
        }
        return $result;
    }
}
  • Have you tested this ? I want this on my checkout page. When i input in postcode field. – Yousaf Jan 17 at 9:53
  • yes i have tested this, it is working as per your requirement in both cart and checkout page – Hiren Jan 17 at 10:10
  • Sir its not working. It is still showing free shipping. – Yousaf Jan 17 at 10:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.