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 as users or guest users. Sometimes store owner wants to let purchase items to only logged-in customers and not guest users so that if any guest user comes to the site to purchase anything from the store, the store forces them to create an account with the store for proceeding further. This way the store has a new customer, which is useful for future purposes as the detail of the customer can be used for further marketing and promotional activities. The more the customer base, the more probability of sale conversion. This is also good when you want restricted access to your site.

Let’s start with a new module for hiding Add to cart Button for Guest Users. For this, we will use the Events and Observer concept of Magento (Yes we can directly use the Object manager to check the customer session in the places where the Add to Cart button is added, but that will not be the 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 with this task, you can check our blog about <a href=”https://www.www.bizspice.com/blog/post/how-to-create-events-observers-in-magento-2/”> Events and Observers. </a>

Step 1: As we are creating a new module, obviously, we will first 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 the layout is loaded so that we will check if the customer is logged in or not before the layout is loaded.

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

<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="Bizspice\NoaddtoCart\Observer\AddHandle" />
    </event>
</config>

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

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

Create Bizspice\NoaddtoCart\Observer\AddHandle.php

<?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())
            {
            $layout->getUpdate()->addHandle('guest_user');
            }
          }
}

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

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

app/code/Bizspice/NoaddtoCart/view/frontend/layout

<?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">Bizspice_NoaddtoCart::catalog/product/view/addtocart.phtml</argument>
            </action>
            </referenceBlock>
            <referenceBlock name="category.products.list">
            <action method="setTemplate">
                         <argument name="template" xsi:type="string">Bizspice_NoaddtoCart::catalog/product/list.phtml</argument>
            </action>
            </referenceBlock>
         </body>
</page>

Here we are overriding two files with this layout, one for the product page and the other one for the catalog page. These two phtml files will be loaded when the customers 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

Addtocart.phtml

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

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

<!--  <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>
                </button>
           </form> -->

Now you have removed add to cart for the 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.