Categories: Magento 2 Tutorials

How to Disable Add to Cart Button in Magento 2

Marketing the upcoming products before its launch is one of the best tactics for their exposure as it makes users curious about those products. There are many ways to market a product but showing on the store is the best one. But it is necessary to have the add to cart button on that product disabled before it is officially available. By default, Magento 2 does not provide the feature to disable the add to cart button on specific products. There are some queries from users on how to implement it. After a long research and implementation, I have accomplished this task and so, today I am going to teach you how to disable the Add to Cart button in Magento 2. I will create a custom module for it, as editing core files are always the worst part. Before learning this guide, it is necessary that you know about custom modules in Magento 2. For that, you can refer this guide: How to Create a Module in Magento 2 Let’s Start!

Steps to Follow

Create Directories

Create Module

Create module.xml file in app/code/Magenticians/Mymodule/etc and add the following code in it:
<?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="Magenticians_Mymodule" setup_version="1.0.0"></module>
</config>
Create registration.php file in app/code/Magenticians/Mymodule and add the following code in it:
<?php

\Magento\Framework\Component\ComponentRegistrar::register(
   \Magento\Framework\Component\ComponentRegistrar::MODULE,
   'Magenticians_Mymodule',
   __DIR__
);

Create Attribute and Attribute Set

Create InstallData.php file in app/code/Magenticians/Mymodule/Setup and add the following code in it:
<?php

namespace Magenticians\Mymodule\Setup;
use Magento\Eav\Setup\EavSetup;
use Magento\Eav\Setup\EavSetupFactory;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Catalog\Setup\CategorySetupFactory;
use Magento\Eav\Model\Entity\Attribute\SetFactory as AttributeSetFactory;


class InstallData implements InstallDataInterface
{
   private $eavSetupFactory;
   private $attributeSetFactory;
   private $attributeSet;
   private $categorySetupFactory;
   public function __construct(EavSetupFactory $eavSetupFactory, AttributeSetFactory $attributeSetFactory, CategorySetupFactory $categorySetupFactory )
       {
           $this->eavSetupFactory = $eavSetupFactory;
           $this->attributeSetFactory = $attributeSetFactory;
           $this->categorySetupFactory = $categorySetupFactory;
       }



   public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
   {
       $setup->startSetup();

               // CREATE ATTRIBUTE SET

       $categorySetup = $this->categorySetupFactory->create(['setup' => $setup]);
       $attributeSet = $this->attributeSetFactory->create();
       $entityTypeId = $categorySetup->getEntityTypeId(\Magento\Catalog\Model\Product::ENTITY);
       $attributeSetId = $categorySetup->getDefaultAttributeSetId($entityTypeId);
       $data = [
           'attribute_set_name' => 'DisableAddToCart',
           'entity_type_id' => $entityTypeId,
           'sort_order' => 200,
       ];
       $attributeSet->setData($data);
       $attributeSet->validate();
       $attributeSet->save();
       $attributeSet->initFromSkeleton($attributeSetId);
       $attributeSet->save();



               // CREATE PRODUCT ATTRIBUTE

       $eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);

           $eavSetup->addAttribute(
                   \Magento\Catalog\Model\Product::ENTITY,
               'text_add_to_cart',
               [
                   'type' => 'varchar',
                   'label' => 'Add to Cart Text',
                   'backend' => '',
                   'input' => 'text',
                   'wysiwyg_enabled'   => false,
                   'source' => '',
                   'required' => false,
                   'sort_order' => 5,
                   'global' => \Magento\Catalog\Model\ResourceModel\Eav\Attribute::SCOPE_STORE,
                   'used_in_product_listing' => true,
                   'visible_on_front' => fasle,
                   'attribute_set' => 'DisableAddToCart',
           ]
       );  
       $setup->endSetup();
   }

} ?>
In the above code I have created the attribute set ‘DisableAddToCart’ and attributed it with code ‘text_add_to_cart’ and label ‘Add to Cart Text’. I have also assigned this attribute in the created attribute set.

Override addtocart.phtml

  • Go to vendor/magento/module-catalog/view/frontend/templates/product/view from the root directory of your store and search addtocart.phtml file.
  • Copy this file in app/code/Magenticians/Mymodule/view/frontend/templates/catalog/product/ view.
Create catalog_product_view.xml file in app/code/Magenticians/Mymodule/view/frontend/layout and add this code in the file:
<?xml version="1.0"?>

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
   <body>
       <referenceBlock name="product.info.addtocart">
           <action method="setTemplate">
               <argument name="template" xsi:type="string">Magenticians_Mymodule::catalog/product/view/addtocart.phtml</argument>
           </action>
       </referenceBlock>
   </body>
</page>
The purpose of above file is to override the addtocart file with our newly created addtocart file (app/code/Magenticians/Mymodule/view/frontend/templates/catalog/product/view/ addtocart.phtml)

Disable Add to Cart Button

Now to disable the add-to-cart button, go to app/code/Magenticians/Mymodule/view/frontend/templates/catalog/product/view and open the addtocart.phtml file. Now search <?php $buttonTitle = __(‘Add to Cart’); ?> and paste the following code just after it: Note:
  • I have added class disablebtn in <div class=”actions disablebtn”>  which I will use in CSS file.
  • I have added disabled in the button tag to disable the button
<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$product = $objectManager->get('Magento\Framework\Registry')->registry('current_product');
$attributeSet = $objectManager->create('Magento\Eav\Api\AttributeSetRepositoryInterface');
$attributeSetRepository = $attributeSet->get($product->getAttributeSetId());
$attribute_set_name = $attributeSetRepository->getAttributeSetName();
?>

<?php if ($attribute_set_name=="DisableAddToCart"):?>
<div class="box-tocart">
   <div class="fieldset">
      <div class="actions disablebtn">
           <button type="submit"
                   class="action primary tocart"
                   id="product-addtocart-button" disabled>
                    <?php echo $_product->getData('text_add_to_cart'); ?>
           </button>
           <?= $block->getChildHtml('', true) ?>
       </div>
   </div>
</div>
<?php else : ?>
And at the end of the addtocart file code, just add <?php endif; ?> . Your final addtocart.phtml file will look like this:
<?php

/**

* Copyright © Magento, Inc. All rights reserved.

* See COPYING.txt for license details.

*/

// @codingStandardsIgnoreFile
/** @var $block \Magento\Catalog\Block\Product\View */?>

<?php $_product = $block->getProduct(); ?>

<?php $buttonTitle = __('Add to Cart'); ?>

<?php

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$product = $objectManager->get('Magento\Framework\Registry')->registry('current_product');
$attributeSet = $objectManager->create('Magento\Eav\Api\AttributeSetRepositoryInterface');
$attributeSetRepository = $attributeSet->get($product->getAttributeSetId());
$attribute_set_name = $attributeSetRepository->getAttributeSetName();
?>

<?php if ($attribute_set_name=="DisableAddToCart"):?>
<div class="box-tocart">
   <div class="fieldset">
      <div class="actions disablebtn">
           <button type="submit"     
                   class="action primary tocart"
                   id="product-addtocart-button" disabled>
                    <?php echo $_product->getData('text_add_to_cart'); ?>
           </button>
           <?= $block->getChildHtml('', true) ?>
       </div>
   </div>
</div>
<?php else : ?>

<?php if ($_product->isSaleable()): ?>
<div class="box-tocart">
   <div class="fieldset">
       <?php if ($block->shouldRenderQuantity()): ?>
       <div class="field qty">
           <label class="label" for="qty"><span><?= /* @escapeNotVerified */ __('Qty') ?></span></label>
           <div class="control">
               <input type="number"
                      name="qty"
                      id="qty"
                      value="<?= /* @escapeNotVerified */ $block->getProductDefaultQty() * 1 ?>"
                      title="<?= /* @escapeNotVerified */ __('Qty') ?>"
                      class="input-text qty"
                      data-validate="<?= $block->escapeHtml(json_encode($block->getQuantityValidators())) ?>"
                      />
           </div>
       </div>
       <?php endif; ?>


<div class="actions">
           <button type="submit"
                   title="<?= /* @escapeNotVerified */ $buttonTitle ?>"
                   class="action primary tocart"
                   id="product-addtocart-button">
               <span><?= /* @escapeNotVerified */ $buttonTitle ?></span>
           </button>
           <?= $block->getChildHtml('', true) ?>
       </div>
   </div>
</div>

<?php endif; ?>
<?php if ($block->isRedirectToCartEnabled()) : ?>
<script type="text/x-magento-init">
   {
       "#product_addtocart_form": {
           "Magento_Catalog/product/view/validation": {
               "radioCheckboxClosest": ".nested"
           }
       }
   }
</script>
<?php else : ?>
<script type="text/x-magento-init">
   {
       "#product_addtocart_form": {
           "Magento_Catalog/js/validate-product": {}
       }
   }
</script>
<?php endif; ?>

<?php endif; ?>
Now it’s time to create a CSS file. Go to app/code/Magenticians/Mymodule/view/frontend/web/css and create disableaddtocart.css file. Add the following code in it:
.disablebtn
{
   cursor: not-allowed;
}
Now just update the catalog_product_view.xml by going to app/code/Magenticians/Mymodule/view/frontend/layout/catalog_product_view.xml in order to integrate CSS file. Final catalog_product_view.xml will look like this:
<?xml version="1.0"?>

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
  <head>
        <css src="Magenticians_Mymodule::css/disableaddtocart.css"/>
   </head>

   <body>
       <referenceBlock name="product.info.addtocart">
           <action method="setTemplate">
               <argument name="template" xsi:type="string">Magenticians_Mymodule::catalog/product/view/addtocart.phtml</argument>
           </action>
       </referenceBlock>
   </body>
</page>

Run CLI Commands

php bin/magento module:enable Magenticians_Mymodule
php bin/magento setup:upgrade
php bin/magento setup:di:compile
php bin/magento setup:static-content:deploy
php bin/magento cache:clean
php bin/magento cache:flush
Now open the admin panel of your store and go to STORES → Attribute Set. You will see new attribute DisableAddToCart: Now click on DisbaleAddToCart and you will see attribute text_add_to_cart: Go to your product edit page and select DisableAddToCart from Attribute Set drop down. Then add the text of your choice which you want to show on a disabled add to cart button: Now just go to the product frontend page and you will see the desired result:

Make Unlimited Customizations to Your Ecommerce Store.

With Cloudways, Deploy Your Magento Store in Minutes and Add as many Customizations to it as you want.

Final Words

Creating hype of the product before its launch can help in getting more sales after its launch. After following this tutorial, I believe that you are now able to disable the add to cart button in Magento 2 store. Still, have any issue or want to discuss anything related to this guide, just leave a comment below!
Syed Muneeb Ul Hasan

Syed Muneeb Ul Hasan is an expert in PHP and Magento, he prefers to educate users in implementing and learning Magento. When not working, he loves to watch cricket.

View Comments

  • Hi just wanna say thanks for your website easy to use :)
    but i have a slight issue when doing the de compile i get error with this file InstallData.php parse error: synax error, unexpected ' privarte' (t_string) , EXPECTING FUNCTION (T_FUNCTION) IN InstallData.php LINE 15

Share
Published by
Syed Muneeb Ul Hasan

Recent Posts

Building Employee Trust and Dedication – A Complete Guide

In the highly competitive modern workplace, trust, and employee loyalty are crucial factors for long-term… Read More

3 months ago

12 Winning Strategies for Small Businesses Marketing

In the ever-evolving world of small business developing and implementing effective marketing strategies is critical to… Read More

3 months ago

Top 10 App Development Companies in Dubai 2024

With one of the highest internet penetration rates, the UAE has set out to revolutionize… Read More

3 months ago

Transforming Industries: How Amazons GPT44X is Revolutionizing AI Technology

Artificial Intelligence (AI) has been continually evolving, leading to remarkable advancements in various industries. Among… Read More

8 months ago

Top Magento 2 Extensions for 2023

Extensions, extensions and lots of extensions. We all love extensions, don’t we? After all, extensions… Read More

11 months ago

Unleashing the Power of Software Testing: Cooperating with a Testing Firm

Software quality is crucial to a firm's success across industries in the quickly changing digital… Read More

11 months ago