I had the same problem and found a solution. I used Magento 2.2.
Basically you just have to listen for the customer_logout
event and when it occures, clear the cart contents. The listening is done via an observer.
- Create a custom module if you havn't already
- In the module, create the file
/etc/frontend/events.xml
if it is not already present
- The
events.xml
should look like this:
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<!-- Your other observers, if any -->
<!-- Copy from here -->
<event name="customer_logout"> <!-- use one of the events above -->
<observer name="[Vendor]_[Name]" instance="[Vendor]\[Name]\Observer\Logout" />
</event>
<!-- to here -->
</config>
- Set your modules's
[Vendor]
and [Name]
accordingly
- In the module, create the file
/Observer/Logout.php
- The content of the Logout observer class should look like this:
<?php
namespace [Vendor]\[Name]\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Checkout\Model\Cart;
class Logout implements ObserverInterface
{
protected $cart;
public function __construct(Cart $modelCart) {
$this->cart = $modelCart;
}
public function execute(\Magento\Framework\Event\Observer $observer)
{
foreach($this->cart->getItems() as $item)
{
$this->cart->removeItem($item->getId());
}
$this->cart->save();
$this->cart->saveQuote(); // I added both 'save' lines to make sure everything is persisted
return $this;
}
}
- Make sure to enter
[Vendor]
and [Name]
accordingly to your module and events.xml
- Run
php bin/magento setup:di:compile
to set the observer active