Magento2 How can I hide flatrate shipping for particular category products?
Any advice will be appreciable
Magento Stack Exchange is a question and answer site for users of the Magento e-Commerce platform. It only takes a minute to sign up.
Sign up to join this communityI 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!