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.

Stay in touch

For a daily email update, click HERE or enter your email and stay on top of things by receiving weekly news in your inbox.

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>