How to check display shipping method base on condition ?

How to check display shipping method base on condition ?

In magento 2, as we know we have free shipping is shipping base on price to display, we can make other shipping display base on condition (based on order total, country, …). In this article, we will take an example to check whether dispay a shipping method based on price as below.

In price like free shipping easy, you can follow my step:

Firstly, you must rewrite Magento\OfflineShipping\Model\Carrier\Flatrate or what shipping you want, here is the example shipping i want to display base on price. You rewrite function \Magento\OfflineShipping\Model\Carrier\Flatrate::collectRates(RateRequest $request).

$path = 'carriers/freeshipping/free_shipping_subtotal';
$minimumOrder = $this->_scopeConfig->getValue(
    $path,
    \Magento\Store\Model\ScopeInterface::SCOPE_STORE,
    $this->getStore()
);
if ($shippingPrice !== false) {
    /** @var \Magento\Quote\Model\Quote\Address\RateResult\Method $method */
    $method = $this->_rateMethodFactory->create();
 
    $method->setCarrier('flatrate');
    $method->setCarrierTitle($this->getConfigData('title'));
 
    $method->setMethod('flatrate');
    $method->setMethodTitle($this->getConfigData('name'));
 
    if ($request->getFreeShipping() === true || $request->getPackageQty() == $this->getFreeBoxes()) {
        $shippingPrice = '0.00';
    }
 
    $method->setPrice($shippingPrice);
    $method->setCost($shippingPrice);
 
    $result->append($method);
}

You can see that code above, in if condition we must satisfy condition shipping price != false and the shipping will display, now we will add the code bellow to if condition

if ($shippingPrice !== false && $request->getBaseSubtotalInclTax() < $minimumOrder)

“$request->getBaseSubtotalInclTax()”: it will take subtotal of your order

$minimumOrder”: is the path in config minimum order in backend of freeshipping because our requirement is base on minimum order of freeshipping, this varable is the price you want to base on to display. Now the free shipping is get subtotal > minimum order to display, but flatrate we must make subtotal < minimum order of freeshipping to display.

After rewrite this class, you can check in the frontend checkout if your order < $50 it’s just display flatrate, if your order > $50 it’s just display freeshipping.

I hope this guide is helpful to you to develop in the future.

Comment

There is no comment on this post. Be the first one.

Leave a comment