Magento – Magento 2 : How to Setup Persistent Shopping cart

cartmagento2persistent

How to enable persistent shopping cart in magento 2.1?

I want to do clear cart item on user sign out from sites. I have already setup from

Stores -> Configuration -> Customers -> Persistent Shopping Cart

Enable Persistence set to Yes,

Clear Persistence on Sign Out set to Yes

But nothing affect in cart items.

How to do this using persistent shopping cart functionality in magento 2?

Goal: Remove Cart item when customer become logout.

Best Answer

Please make change in following setting. Go to following setting in admin:

Stores > Configuration > Customers > Persistent Shopping Cart

Persist Shopping Cart set to No If still it'll not work. Make small module like following.


To remove Cart item when customer logout. You can make small module for this functionality. The code is verified and it is working in Magento 2.1.

app/code/Rohit/UserCart/registration.php

<?php

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

app/code/Rohit/UserCart/etc/module.xml

<?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="Rohit_UserCart" setup_version="1.0.0" >
    </module>
</config>

app/code/Rohit/UserCart/etc/frontend/events.xml

<?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="customer_logout">
        <observer name="clearCartOnLogout" instance="Rohit\UserCart\Observer\EmptyCartLogout" />
    </event>
</config>

app/code/Rohit/UserCart/Observer/EmptyCartLogout.php

<?php

namespace Rohit\UserCart\Observer;

use Magento\Framework\Event\ObserverInterface;
use Magento\Checkout\Model\Cart as CustomerCart;

/**
 * Class EmptyCartLogout
 * @package Rohit_UserCart
 */
class EmptyCartLogout implements ObserverInterface
{
    /**
     * @var CustomerCart
     */
    protected $cart;

    /**
     * EmptyCartLogout constructor.
     * @param CustomerCart $cart
     */
    public function __construct(
        CustomerCart $cart

    ){
        $this->cart = $cart;
    }

    /**
     * @param \Magento\Framework\Event\Observer $observer
     */
    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        $this->cart->truncate()->save();
    }
}

After that run following command at your magento root

php bin/magento module:enable Rohit_UserCart

php bin/magento setup:upgrade

Hope this will helpful to you