How to disable Add to Cart option for the whole store in Magento 2.

Sometimes few companies just want to showcase their products for a certain time. They may have a plan to lunch add to cart option later or lunch later with some others fixing. In those cases, it needs to disable the cart system for the whole store.

Now I am going to show you how can we disable the cart system using a small module.

Basically, you need to return false in isSalable method in the Magento\Catalog\Model\Product class. So, you can write an after plugin method for this isSalable method. Plugin (Interceptor) is a way to overwrite core functionalities in Magento 2. Please follow these steps below to create a small module.

app/code/MilanDev/DisableCart/registration.php

<?php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'MilanDev_DisableCart',
    __DIR__
);

app/code/MilanDev/DisableCart/etc/module.xml

<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="MilanDev_DisableCart" setup_version="1.0.0">
        <sequence>
            <module name="Magento_Catalog"/>
        </sequence>
    </module>
</config>

This is the file where you need to inject your class and tell that your method will be run after isSalable method.
app/code/MilanDev/DisableCart/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\Catalog\Model\Product">
        <plugin disabled="false" name="MilanDev_DisableCart_Plugin_Magento_Catalog_Model_Product" sortOrder="10" type="MilanDev\DisableCart\Plugin\Magento\Catalog\Model\Product"/>
    </type>
</config>

Notice the afterIsSalable method. In order to run this method immediately after isSalable method, we must add an after prefix in our newly created method (afterIsSalable).
app/code/MilanDev/DisableCart/Plugin/Magento/Catalog/Model/Product.php

<?php
namespace MilanDev\DisableCart\Plugin\Magento\Catalog\Model;

class Product
{
    public function afterIsSalable(
        \Magento\Catalog\Model\Product $subject,
        $result
    ) {
        return false;
    }
}

Run the following commands in your Magento root directory.

php bin/magento module:enable MilanDev_DisableCart -c
php bin/magento setup:upgrade
php bin/magento setup:di:compile
php bin/magento cache:flush

If you have a preferred method in this topic. Please let me know in the comments. Happy Coding!

Leave a Reply

Your email address will not be published. Required fields are marked *