0

Magento2 How can I hide flatrate shipping for particular category products?

Any advice will be appreciable

1 Answer 1

0

I think the best way is to create a plugin for CollectRates for Magento\OfflineShipping\Model\Carrier\Flatrate. I would do it like this:

app/code/StackExchange/HideFlatRateForCategories/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"
>
    <type name="Magento\OfflineShipping\Model\Carrier\Flatrate">
        <plugin name="HideFlatRateForSomeCategories"
                type="StackExchange\HideFlatRateForCategories\Plugin\HideFlatRateForSomeCategories"
        />
    </type>
</config>

app/code/StackExchange/HideFlatRateForCategories/Plugin/HideFlatRateForSomeCategories.php

<?php
declare(strict_types=1);

namespace StackExchange\HideFlatRateForCategories\Plugin;

use Magento\Checkout\Model\Session;

class HideFlatRateForSomeCategories
{
    /**
     * @var Session
     */
    private Session $checkoutSession;

    public function __construct(
        Session $checkoutSession
    ) {
        $this->checkoutSession = $checkoutSession;
    }

    public function afterCollectRates(\Magento\OfflineShipping\Model\Carrier\Flatrate $flatrate, $result)
    {
        // enter the categories you want to exclude here:
        $categories = [4, 6];
        $quote = $this->checkoutSession->getQuote();

        $items = $quote->getAllItems();
        /** @var \Magento\Quote\Model\Quote\Item $item */
        foreach ($items as $item) {
            if (!empty(array_intersect($item->getProduct()->getCategoryIds(), $categories))) {

                return false;
            }
        }

        return $result;
    }
}

Good luck!

1
  • Hello it worked fine. Can u suggest me something on how can I stop a particular category product from adding to cart when another exists? Like if A category product is present you can't add B category product & vice verse...
    – Arjun
    Nov 3, 2020 at 13:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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