Categories
Magento PHP

Magento : How to Update Product Price In Cart Programmatically

If you want to add a product to magento cart with price change then let me tell you that we can update product price at the time of adding product in cart in magento by using following code.

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.

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 Reply

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