How To Restrict “Add To Cart” Using Plugin In Magento 2
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:
123456789<?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:
123456789101112131415161718192021222324<?phpnamespace [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.
Any doubts? Please mention them in the Comments section below and I’d be happy to help.
Do share the post with the Magento community via social media.
Thank you.
Sanjay Jethva
Sanjay is the co-founder and CTO of Meetanshi with hands-on expertise with Magento since 2011. He specializes in complex development, integrations, extensions, and customizations. Sanjay is one the top 50 contributor to the Magento community and is recognized by Adobe.
His passion for Magento 2 and Shopify solutions has made him a trusted source for businesses seeking to optimize their online stores. He loves sharing technical solutions related to Magento 2 & Shopify.
Prev
6 Easy Steps to Create 301 Redirect In Magento 2
How To Add CSS & Javascript Files To CMS Pages In Magento 2
Next