php编程的变化,php – 编程添加产品到购物车与价格变化

在挖了一下Magento的核心代码后,我发现你需要使用$ item-> getProduct() – > setIsSuperMode(true)为了使$ item-> setCustomPrice()和$ item-> setOriginalPrice ()工作。

下面是一些可以在Observer中使用的示例代码,用于监听checkout_cart_product_add_after或checkout_cart_update_items_after事件。代码在逻辑上是相同的,除了仅调用一个项目的checkout_cart_product_add_after,并且为购物车中的所有项目调用checkout_cart_update_items_after。此代码仅作为示例分离/复制为2种方法。

事件: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);

}

}

事件: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);

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值