Wednesday , May 24 2017
Home >> All tutorial >> 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

Ready to foster your knowledge with MAGENTO 2 BASIC GUIDE

The new Order Success combo with Magento 2 Inventory Management, Magento 2 Order Fulfillment, Magento 2 Dropship, Magento 2 Barcode Management and Magento 2 Purchase Management

Is your site still a mess and Magento extensions are not enough to save your site? Save your site with Magento Web Development Services now

magento services


About Champ

Leave a Reply

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