Show add to cart button to logged in customers only

Show add to cart button to logged in customers only

In Magento 2,  Add To Cart Button is available by default for all user groups whether they are logged in users or guest users. Sometime store owner wants to let purchase item from logged in customer and not to guest user, so that if any guest user comes to site for purchasing anything from store, store forced them to create an account with store for processing further and by this way store has a new customer and this is useful for future purpose as the detail of customer can be used for further marketing and promotional activities. More customer base, more probability of sale conversion. This is also good when you want a restricted access for your site.


Let’s start with a new module for hiding Add to cart Button for Guest Users. For this we will use Events and Observer concept of Magento (Yes we can directly use Object manager to check customer session on the places where Add to Cart button is added, but that will not be standard way and also not a right approach as this will consume too much server resource).

So, if you need to learn more about Events and Observer before proceeding in this task, you can check our blog about <a href=””> Events and Observers. </a>


Step 1: As we are creating new module so obviously create registration.php and module .xml. Here we will start by creating an event.xml file. In which we will describe that event will be triggered before layout is loaded, so that we will check if customer is logged in or not before layout is loaded.


Create app/code/Bizspice/NoaddtoCart/etc/frontend/events.xml


<config xmlns:xsi="" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="layout_load_before">
         <observer name="add_layout_handles" instance="Bizspice\NoaddtoCart\Observer\AddHandle" />


Here layout_load_before is an event in which we are defining an observer named AddHandle where we will add new handle according to our condition.


Step 2: Now we will create observer file named AddHandle.php (defined in events.xml) where we will add new handle according to customer session.


Create Bizspice\NoaddtoCart\Observer\AddHandle.php


namespace Bizspice\NoaddtoCart\Observer;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Customer\Model\Session as CustomerSession; 
class AddHandle 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())


Here in the observer file, in constructor we have added customer session and then use this condition to check if customer is logged in or not and added a handle named guest_user in layout if customer is not logged in.


Step 3: As in Observer file we have added a new handle 'guest_user' in layout for customer who are not logged in on store, so we have to create a layout file name guest_user.xml in




<?xml version="1.0"?>
<page xmlns:xsi="" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
          <referenceBlock name="">
           <action method="setTemplate">
                       <argument name="template" xsi:type="string">Bizspice_NoaddtoCart::catalog/product/view/addtocart.phtml</argument>
            <referenceBlock name="category.products.list">
            <action method="setTemplate">
                         <argument name="template" xsi:type="string">Bizspice_NoaddtoCart::catalog/product/list.phtml</argument>


Here we are overriding two files with this layout, one for product page and other for catalog page. These two phtml file will loaded when customer are not logged in.


Step 4:  Here In the guest_user.xml, we have set the path of addtocart.phtml and list.phtml file for guest users. Create addtocart.phtml and list.phtml




 $_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>
<?php endif; ?>




Copy list.phtml from vendor and put it into your module at catalog/product/list.phtml , and remove or comment this section from list.phtml.


<!--  <form data-role="tocart-form" data-product-sku="<?= $block->escapeHtml($_product->getSku()) ?>" action="<?= /* @NoEscape */ $postParams['action'] ?>" method="post">
                 <input type="hidden" name="product" value="<?= /* @escapeNotVerified */ $postParams['data']['product'] ?>">
                 <input type="hidden" name="<?= /* @escapeNotVerified */ Action::PARAM_NAME_URL_ENCODED ?>" value="<?= /* @escapeNotVerified */ $postParams['data'][Action::PARAM_NAME_URL_ENCODED] ?>">;
                 <?= $block->getBlockHtml('formkey') ?>
                <button type="submit"  title="<?= $block->escapeHtml(__('Add to Cart')) ?>"
                    class="action tocart primary">
                         <span><?= /* @escapeNotVerified */ __('Add to Cart') ?></span>
           </form> -->


Now you have removed add to cart for guest user from catalog and product page




In our next article we will help you to hide catalog pricing, etc on home/product/category/search etc pages to make a private sale site. Stay tuned for our next article on this.