Magento : How to Update Product Price In Cart Programmatically

If you want to Add Product to Magento Cart with Price Change then you have to write an Observer that listens the “checkout_cart_product_add_after” or “checkout_cart_update_items_after” event.
You need to modify the code as shown below.

The code is same except checkout_cart_product_add_after is called for only one item and checkout_cart_update_items_after is called for all items in the cart.

Step 1. Open etc/config.xml of your module. CodeMasterz is company name and CustomDiscount is your module name

<?xml version="1.0"?>
<config>
    <modules>
       ...
    </modules>
    <global>
        <models>
           ...
        </models>
		
		<!--Creating a observer for custom discount on cart page by Vaseem-->
		<events>
            <checkout_cart_product_add_after>
                <observers>
                    <unique_event_name>
                        <class>CodeMasterz_CustomDiscount_Model_Observer</class>
                        <method>myCustomDiscount</method>
                    </unique_event_name>
                </observers>
            </checkout_cart_product_add_after>
        </events>
		
        ...
    </global>
</config>

Step 2. Then create a file in your module folder “Model/Observer.php”

<?php
class CodeMasterz_CustomDiscount_Model_Observer
{
    
    public function myCustomDiscount(Varien_Event_Observer $observer)
    {
        $item = $observer->getQuoteItem();
        if ($item->getParentItem()) {
            $item = $item->getParentItem();
        }
        //discount 20% off
        $discount = 0.20; 
        // Check if the discount isn't applied over and over while refreshing
        //$specialPrice = $item->getPrice() - ($item->getPrice() * $discount);
		$specialPrice	=	125;
		
        if ($specialPrice > 0) {
            $item->setCustomPrice($specialPrice);
            $item->setOriginalCustomPrice($specialPrice);
            $item->getProduct()->setIsSuperMode(true);
        }
    }
?>

Hope above works for you. If you have any difficulty understanding the code or anything else then you can contact me using contact page at this website.

By Vaseem Ansari

I’m Vaseem, a Software Engineer by Profession, a Traveler, a Foodie by Heart and the founder of VaseemAnsari.com. I started traveling from college days and it has become a part of me now. So when ever I happen to get a chance I pack my bag and am on the roads. You can follow me on these social networks Facebook, Twitter, Google+ and Linkedin.

Leave a comment

Your email address will not be published. Required fields are marked *