Magento 2 Tutorials

Magento 2: Hide Add to Cart Button for Guest Users

hide add to cart guest users magento 2

Magento 2 has become the yardstick for ecommerce platforms because of the multitude of the awesome features and great user experience of the platform.

By default, on Magento 2 powered store, Add to Cart button is always available for guest users. However, store owners have different requirements and there is always the case where the store owners do not wish the visibility of the button to guest users.

In this tutorial, I am going to show you how you could easily disable or hide Add to Cart button in Magento 2 for guest users. Following the best Magento code development practices, I will start by creating a custom module.

Create the Module

Begin by configuring and registering the module. Create module.xml in app/code/Magenticians/Mymodule/etc and add this code to the file:

<?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.1"></module>
</config>

Next, create registration.php in app/code/Magenticians/Mymodule and add this code to the file

<?php

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

At this point, I can direct use Object Manager in the module addtocart.phtml to check the session of the user. However, this is not the right approach because it wastes too many server resources on unnecessary calls. I did some research and got inspired by Frank Clark’s Guide

Create Event and Observer

Before going further, I think it is important to understand events and observers in Magento 2:

Magento 2 Events

When a specific action is triggered, the event is dispatched by Magento modules in order to pass data to the relevant Observer configured for the dispatched event.

Magento 2 Observers

Observers are used to catch the action which was triggered from events. In observers, you can set the required functionality or logic that is to be executed in response.

To learn more about Magento 2 Events and Observers, check out the DevDocs documentation.

Now, I will create an event which will be triggered before the layout is loaded. This will help in checking the session of the customer. To do this, create events.xml in app/code/Magenticians/Mymodule/etc/frontend and add this code:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="layout_load_before">
        <observer name="add_layout_handles" instance="Magenticians\Mymodule\Observer\AddHandles" />
    </event>
</config>

Next, create AddHandles.php in app/code/Magenticians/Mymodule/Observer and add this code to the file:

<?php

namespace Magenticians\Mymodule\Observer;

use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Customer\Model\Session as CustomerSession;

class AddHandles implements ObserverInterface
{
    protected $customerSession;
    public function __construct(CustomerSession $customerSession)
    {
        $this->customerSession = $customerSession;
    }

    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        $layout = $observer->getEvent()->getLayout();

//To check that customer is logout
        if (!$this->customerSession->isLoggedIn())
        {
            $layout->getUpdate()->addHandle('customer_logged_out');
        }
    }
}

In the above code, you can see the constructor where I have added customer session. Then, in the execute() function, I added the handle customer_logged_out to the layout. To use this handle, create a layout file customer_logged_out.xml in app/code/Magenticians/Mymodule/view/frontend/layout and add this code to it:

<?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>

Create the phtml File

In the customer_logged_out.xml, I have set the path of addtocart.phtml file for guest users. So, you have to create addtocart.phtml in app/code/Magenticians/Mymodule/view/frontend/templates/catalog/product/view and add this code to the file:

<?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 if ($_product->isSaleable()): ?>

<div class="box-tocart">
        <p>Please <a href="<?php echo $block->getUrl('customer/account/login') ?>" title="<?php echo __('Login') ?>"><?php echo __('Login') ?></a> or <a href="<?php echo $block->getUrl('customer/account/create') ?>" title="<?php echo "Register" ?>"><?php echo "Register" ?></a> to buy this product!</p>
</div>

<?php endif; ?>

Run CLI Commands

Launch the SSH terminal and run the following commands in the root directory of your store:

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

Check the Result

It is time to check the results. Go to any product frontend page as a guest user and you will see that Add to Cart button is not visible.

hide add to cart button magento 2 for guest users

Final Words

I believe that you are now able to hide Add to Cart button in Magento 2 from guest users. If you are facing any issue related to this tutorial, just leave your comment below and I will get back to you.

Subscribe Newsletter

Subscribe to get latest Magento news

40% Off for 4 Months on Magento Hosting + 30 Free Migration