Programmatically Add Product to Cart with Price Change

Add a product to cart programmatically with discount applied

Posted on March 29, 2016 in Magento

Suppose, your product’s price $100. You wanted to change it to $90 when added to Cart. You have to use $item->getProduct()->setIsSuperMode(true) in order to make $item->getCustomPrice() and $item->getOriginalPrice() work.

Here is some sample code you can use within an Observer that listens for the checkout_cart_product_add_after or checkout_cart_update_items_after events. The code is logically the 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.

Event: checkout_cart_product_add_after


public function applyDiscount(Varien_Event_Observer $observer) 
{
    $item = $observer->getQuoteItem();
    if($item->getParentItem()) {
        $item = $item->getParentItem();
    }

    $percentDiscount = 0.1;

    //This makes sure the discount isn't applied over and over when refreshing
    $specialPrice = $item->getOriginalPrice() - ($item->getOriginalPrice() * $percentDiscount);

    //Make sure we don't have a negative
    if($specialPrice > 0) {
       $item->setCustomPrice($specialPrice);
        $item->setOriginalCustomPrice($specialPrice);
        $item->getProduct()->setIsSuperMode(true); // this is need to make setCustomPrice working.
    }
}

Event: checkout_cart_update_items_after


public function applyDiscounts(Varien_Event_Observer $observer) 
{
    foreach($observer->getCart()->getQuote()->getAllVisibleItems() as $item )
    {
        if($item->getParentItem()) {
            $item->$item->getParentItem();
        }

        $percentDiscount = 0.1;

         //This makes sure the discount isn't applied over and over when refreshing
        $specialPrice = $item->getOriginalPrice() - ($item->getOriginalPrice() * $percentDiscount);

        //Make sure we don't have a negative
        if($specialPrice > 0) {
            $item->setCustomPrice($specialProduct);
            $item->setOriginalCustomPrice($specialPrice);
            $item->getProduct()->setIsSuperMode(true);
        }
    }
}


comments powered by Disqus