You Are Here: Home » Magento tutorials » How to Programmatically Add Product to Cart with Price Change in Magento

How to Programmatically Add Product to Cart with Price Change in Magento

How to Programmatically Add Product to Cart with Price Change in Magento

Use the following code to programmatically add product to cart with price change:

Event: checkout_cart_product_add_after

/** * @param Varien_Event_Observer $observer */ 
public function applyDiscount(Varien_Event_Observer $observer) 
{
 /* @var $item Mage_Sales_Model_Quote_Item */ 
$item = $observer->getQuoteItem(); 
if ($item->getParentItem()) { 
$item = $item->getParentItem(); 
} 
// Discounted 25% off 
$percentDiscount = 0.25; 
// 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); } }

 

Event: checkout_cart_update_items_after

/** * @param Varien_Event_Observer $observer */ 

public function applyDiscounts(Varien_Event_Observer $observer) { 

foreach ($observer->getCart()->getQuote()->getAllVisibleItems() as $item /* @var $item Mage_Sales_Model_Quote_Item */) 
  { 
if ($item->getParentItem()) 
  { 
$item = $item->getParentItem(); 
  } 
// Discounted 25% off 

$percentDiscount = 0.25; 

// 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); 
 } 
} 
}

 

Recommended readingTop 5 Best magento hosting

About The Author

avatar

Eric is a magento specialist at Magento Tutorial. He loves to share everything related to magento to the community

Number of Entries : 24

Leave a Comment

Scroll to top
" "