Avoid merging old cart items in customer session magento

In this post we will see how to avoid merging old cart items to the current checkout session.

Scenario:

  • It will be happen when we login to store and adds some products into cart and leaves store without purchasing.
  • Then coming back to the store after sometime and adds some product into cart without login and proceeds to checkout.
  • In checkout page we will be requested to login, after login we can see some additional products are added into the cart which we are added in previous session.
  • In this case what we have to do is we need to clear old cart items( It was requested by one of my client ) and allow customers to show with the current session items.

Below i have given the codes used to clear old cart items. And also attached the file. File: app/etc/modules/Ws_Clearoldcartproducts.xml


< ?xml version = "1.0" ?>



true
local



File: app/code/local/Ws/Clearoldcartproducts/etc/config.xml In below code we are using sales_quote_merge_before observer to clear old items. To know about observer go through this link.


< ?xml version = "1.0" ?>



1.0.0







singleton
Ws_Clearoldcartproducts_Model_Observer
loadCustomerQuote






File: app/code/local/Ws/Clearoldcartproducts/Model/Observer.php We have declared our observer class and action names in above xml file. Below code is where our magic works!


< ?php

class Ws_Clearoldcartproducts_Model_Observer extends Mage_Checkout_Model_Session {

/**
* Clears old cart items after login
*
* @return object currently added cart items
*/
public function loadCustomerQuote() {
$customerQuote = Mage::getModel('sales/quote')
->setStoreId(Mage::app()->getStore()->getId())
->loadByCustomer(Mage::getSingleton('customer/session')->getCustomerId());

if ($customerQuote->getId() &
&
$this->getQuoteId() != $customerQuote->getId()) {
// Removing old cart items of the customer.
foreach ($customerQuote->getAllItems() as $item) {
$item->isDeleted(true);
if ($item->getHasChildren()) {
foreach ($item->getChildren() as $child) {
$child->isDeleted(true);
}
}
}
$customerQuote->collectTotals()->save();
} else {

$this->getQuote()->getBillingAddress();
$this->getQuote()->getShippingAddress();
$this->getQuote()->setCustomer(Mage::getSingleton('customer/session')->getCustomer())
->setTotalsCollectedFlag(false)
->collectTotals()
->save();
}
return $this;
}

}
?>

What we have done in above code is we have override the Mage_Checkout_Model_Session::loadCustomerQuote() action to avoid merging of old cart items!. Instead of merging the product we have deleted it! That’s what we done! Please post your feedback’s Thanks 🙂

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: