How to clear item in cart in frontend web page programmatically?

Bong Channarith 06/13/2018. 2 answers, 307 views
magento2.2 frontend shopping-cart quoteitem cart-items

Using magento 2.2, I need to remove all items in current cart while going to other root category on my front page. I want some advice for coding this event.

2 Answers

Vivek 06/13/2018.

You can delete cart items using below code.

public function deleteQuoteItems()
  $checkoutSession = $this->getCheckoutSession();
  $allItems = $checkoutSession->getQuote()->getAllVisibleItems();

    foreach ($allItems as $item) {
     $itemId = $item->getItemId();//item id of particular item
     $quoteItem->delete();//deletes the item

 public function getCheckoutSession()
  $objectManager = \Magento\Framework\App\ObjectManager::getInstance();//instance of object manager 
  $checkoutSession = $objectManager->get('Magento\Checkout\Model\Session');//checkout session

  return $checkoutSession;

public function getItemModel()
 $objectManager = \Magento\Framework\App\ObjectManager::getInstance();//instance of object manager
 $itemModel = $objectManager->create('Magento\Quote\Model\Quote\Item');//Quote item model to load quote item

  return $itemModel;

MiniCart is rendering using Local Storage.

To clear it check here. Very Well Explained.How to add "Empty Cart" button to minicart

Vishnunath 06/13/2018.

Try the below script to delete cartItems.



    use Magento\Framework\App\Bootstrap;
    require dirname(__FILE__) . '/../app/bootstrap.php';

    $bootstrap = Bootstrap::create(BP, $_SERVER);

    $obj = $bootstrap->getObjectManager();
    $state = $obj->get('Magento\Framework\App\State');
    try {
        $checkoutSession = $obj->get('\Magento\Checkout\Model\Session');
        $cart = $obj->get('\Magento\Checkout\Model\Cart');

        $allItems = $checkoutSession->getQuote()->getAllVisibleItems();
        foreach ($allItems as $item) {
            $itemId = $item->getItemId();

        echo "Cleared all";
    } catch (\Exception $e) {
        echo $e->getMessage();

Related questions

Hot questions


Popular Tags