More than 1000+ satisfied clients and counting, since 2010

Blog

Programmatically Add Product to Cart with Price Change in Magento

programmatically Add Product to Cart with Price ChangeMagento Content management System is an easy to use and flexible eCommerce CMS. You can customize the settings for your online store in simple steps. This blog post will cover one such customization for Magento store managers – how to programmatically Add Product to Cart with Price Change.

But before we begin with the tutorial let us first know why some store managers need to do this. Let for instance, the price of a product is $10, but he/she wants to change it to $9. So, how to change it programmatically without giving discounts or changing it manually?

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

This will surely help you to programmatically add product to cart with price change. But, if you unsuccessfully in changing it, then request a quote. Our Magento team will provide you expert guidance for detecting and solving the problems.

We also offer quality Magento services which includes Magento Extension and Website Development, Magento SEO Services and Magento Installation Services. Also do check our Magento Stores for useful Magento extensions for your shopping cart.

Written by

The author didnt add any Information to his profile yet