Prevent Shipping Methods Based on Conditions

Let’s Begin with the new thing today. The most common or I would say, one of the most important too topic of Magento 2. Every Store flow in Magento has to go through this. so we can say it’s a common path for all.

Well Before proceeding with this topic Preventing Shipping. Let discuss the shipping page(Checkout Step 1) first.

Let’s not go into that deep. Just an overview that why we require the Shipping methods. As we all know on the Ecommerce store each product requires a shipping method to make the order successfully delivered to one’s Address.

So, the shipping methods comes many with challenges. Here are few Examples:

Shipping Method customization depends upon factors like Price, weight, products, country, etc.
Show custom message as per conditions and many more.

Here we will apply the condition to prevent Shipping methods depending upon conditions like products, price, weight, for all shipping methods, etc.

Let’s begin with this Step by step.

Let’s start with the Basic Module Structure First. Here I assume one should already Have Basic knowledge about Module and its structure, if not please refer to this link first.

I have created an Excellence_Preventshipping Module.

So, we first have to take an excess of the method which is responsible for filtering and shows valid shipping methods on checkout. Magento uses Shipping.php to validate all shipping methods


Here in this we have to use collectCarrierRates($carrierCode, $request) function.

For this we can either override this model file or use plugin for this around/after/before to validate our conditions.

For now, I am overriding this model.

Let’s create di.xml file to override this class.

Now, as we have overridden the shipping.php class to our vendor files which are at Excellence\Preventshipping\Model\Rewrite\Shipping. So create a file at this path with the same name Shipping.php as we have given in di.xml.

Here in the above section, we have added the condition in collectCarrierRates() function for validation in which we are passing the method name.

Similarly, we can add a condition for price and weight too, depending upon our requirement.

We can also use a plugin in collectCarrierRates() function to do this and return false if our condition gets true.