How to hide/remove the Add to Cart button on magento 2

Sometimes it is useful to remove or hide the Add to Cart button throughout a magento 2 website. An easy way to do this without changing the actual template is by creating a plugin (also called interceptor) to change the isSaleable function that is used on those templates.

Here I created the function that will be called after the isSaleable function defined in the Magento\Catalog\Model\Product class, thus changing it’s functionality:

    public function afterIsSaleable(Product $product)
    {
        return [];
    }

This method will return an empty array instead of the usual logic performed on this method. This will be seen as the product not being saleable and consequently the add to cart button not to be displayed.

This function is implemented in a new Hidecartbutton class of a custom module called Webguru/HideCartButton:

# /app/code/Webguru/HideCartButton/Plugin/Hidecartbutton.php

<?php
namespace Webguru\HideCartButton\Plugin;

use Magento\Catalog\Model\Product;


class Hidecartbutton
{
    public function afterIsSaleable(Product $product)
    {
        return [];
    }
}

Now, we need to tell magento to plug this function after the isSaleable function. This is done in the di.xml file:

# /app/code/Webguru/HideCartButton/etc/di.xml

<?xml version="1.0" encoding="UTF-8"?> 
<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 name="hidecartbutton" type="Webguru\HideCartButton\Plugin\Hidecartbutton" sortOrder="32"/>
    </type>
</config>

The complete code for this module is available in my GitHub, in a repository called HideCartButton that you can download here.

Enjoy 🙂

Leave a Reply

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