How To

How to hide product page Add to Cart Button for Guest Users in Magento 2

By default, Magento store products are visible to all the customer groups as well as no login customers too, including complete details like product name, short description, detailed description, price, customer options and a quick link to add the product to the shopping cart using add to cart button. Once the customer has made up their mind they can shop merchandise by creating an account or in not time customer can quickly checkout product using guest login. However, store owners do not wish to display “add to cart” button to guest users, or you can say not logged in customers to build a substantial customer base or to gather customer details for further marketing or product promotions.

Recently one of our customers wants to hide their “add t cart” button for their store non logged in customers, maybe other store owners also willing to the same so we decided to write a blog. In today’s blog series, I will show you how you could easily hide “Add to Cart” button for Magento 2 guest users.

Simply follow these 4 steps guide and you are done.

Step 1 : Firstly, we need to create an event inside “events.xml” file using below code in our custom extension folder at below path.
app\code\Vendor\Extension\etc\frontend

<?xml version="1.0" encoding="utf-8"?>
<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="Vender\Extension\Observer\Logouthandles" />
  </event>
</config>

Step 2 : Next, we need to create event handler for previously created event in our observer file.
app\code\Vendor\Extension\Observer

<?php
namespace Vendor\Extension\Observer; 
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Customer\Model\Session as CustomerSession;
 
class Logouthandles implements ObserverInterface
{
    protected $customerSession;
    public function __construct(CustomerSession $customerSession)
    {
        $this->customerSession = $customerSession;
    }
 
    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        $layout = $observer->getEvent()->getLayout();
 
        if (!$this->customerSession->isLoggedIn())
        {
            $layout->getUpdate()->addHandle('customer_logged_out');
        }
    }
}

Step 3 : Now we need to create layout “customer_logged_out.xml” file using below code in given path.
app\code\Vendor\Extension\view\frontend\layout

<?xml version="1.0" encoding="utf-8"?> 
<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">Vendor_Extension::catalog/product/view/addtocart.phtml</argument>
            </action>
        </referenceBlock>
    </body>
</page>

Step 4 : And in last step, we have to create “addtocart.phtml” at below path using following code. app\code\Vendor\Extension\view\frontend\templates\catalog\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; ?>

Tadaa! You have successfully hide your product page “add to cart” button for your guest users.
And yes, please hit that stars if this code worked for you or you can comment down below to give your feedback.
Happy Hiding!

Click to rate this post!
[Total: 7 Average: 4.3]
Dhiren Vasoya

Dhiren Vasoya is a Director and Co-founder at MageComp, Passionate 🎖️ Certified Magento Developer👨‍💻. He has more than 9 years of experience in Magento Development and completed 850+ projects to solve the most important E-commerce challenges. He is fond❤️ of coding and if he is not busy developing then you can find him at the cricket ground, hitting boundaries.🏏

Recent Posts

Magento 2: Add Quantity Increment and Decrement on Category Page

Hello Magento Friends, In this blog, we will discuss about adding quantity increment and decrement…

1 day ago

How to Integrate ChatGPT with Laravel Application?

In this guide, we'll explore how to integrate ChatGPT, an AI-powered chatbot, with a Laravel…

4 days ago

What are Net Sales? How to Calculate Your Net Sales?

In the world of business, understanding financial metrics is crucial for making informed decisions and…

7 days ago

Magento 2 Extensions Digest April 2024 (New Release & Updates)

Welcome to the MageComp Monthly Digest, where we bring you the latest updates, releases, and…

7 days ago

The ABCs of Geofencing: Definition, Features and Uses

In this era, businesses are always on the lookout for ways to engage with their…

1 week ago

How to Delete Product Variant in a Shopify Remix App using GraphQL Mutations?

Managing a Shopify store efficiently involves keeping your product catalog organized. This includes removing outdated…

1 week ago