Earlier, I posted a solution to set conditions to restrict adding products in Magento 2.
This time, solving a similar issue, however, with the plugin is implemented in an easier way.
You can use the below code to restrict “Add to Cart” using plugin in Magento 2.
For example, you can restrict a customer to make a purchase of products from different categories. Or, restrict purchasing a demo product for more than once!
Such conditions can be set to restrict adding products to cart in Magento 2 using the below code:
Method to Restrict “Add To Cart” Using Plugin In Magento 2:
- Create di.xml in app/code/[Vendor]/[Module]/etc and add the following code:
<?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\Checkout\Model\Cart"> <plugin name="interceptAddingProductToCart" type="[Vendor]\[Module]\Plugin\Model\Checkout\Cart\Plugin" sortOrder="10" disabled="false"/> </type> </config>
- Create Plugin.php in app/code/[Vendor]/[Module]/Plugin/Model/Checkout/Cart and add the following code:
<?php namespace [Vendor]\[Module]\Plugin\Model\Checkout\Cart; use Magento\Framework\Exception\LocalizedException; class Plugin { public function beforeAddProduct($subject, $productInfo, $requestInfo = null) { try { // Your custom code here. } catch (\Exception $e) { throw new LocalizedException(__($e->getMessage())); } return [$productInfo, $requestInfo]; } }
That’s it.
Or, you could simply use the Magento 2 Call for Price extension to restrict customers to add products to the cart and instead call you for inquiring about pricing.
In a similar way, you can also use the plugin method to restrict orders in Magento 2.
Do share the post with the Magento community via social media.
Thank you.