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

Any advice will be appreciable

1 Answer 1


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


<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    <type name="Magento\OfflineShipping\Model\Carrier\Flatrate">
        <plugin name="HideFlatRateForSomeCategories"



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!

  • 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
    Commented Nov 3, 2020 at 13:41

Your Answer

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

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