在深入研究了Magento的核心代码之后,我发现您需要使用
$item->getProduct()->setIsSuperMode(true)它才能进行制作
$item->setCustomPrice()和
$item->setOriginalPrice()工作。
以下是一些示例代码,您可以在用于监听
checkout_cart_product_add_afteror
checkout_cart_update_items_after事件的Observer中使用。该代码在逻辑上是相同的,除了
checkout_cart_product_add_after只对一项
checkout_cart_update_items_after调用,对购物车中的所有项调用。仅作为示例,此代码被分离/复制为2种方法。
事件:checkout_cart_product_add_after
public function applyDiscount(Varien_Event_Observer $observer){ $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); }}事件: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(); } // 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); } }}


