php 以编程方式将产品添加到购物车并更改价格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5104482/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 16:49:55  来源:igfitidea点击:

Programmatically add product to cart with price change

phpmagento

提问by Mukesh Chapagain

I want to add a product to cart programmatically. Also, I want to change the product price when added to cart.

我想以编程方式将产品添加到购物车。另外,我想在添加到购物车时更改产品价格。

Suppose, my product's price is $100. I wanted to change it to $90 when added to cart.

假设,我的产品的价格是 100 美元。我想在添加到购物车时将其更改为 90 美元。

I added product to cart. However, I am unable to change the product price.

我将产品添加到购物车。但是,我无法更改产品价格。

Is it possible?

是否可以?

Here is the code to add product to cart:-

这是将产品添加到购物车的代码:-

$cart = Mage::getSingleton('checkout/cart');

try {   
    $cart->addProduct($product, array('qty' => 1));
    $cart->save();
}
catch (Exception $ex) {
    echo $ex->getMessage();
}

回答by interimpulso

After digging a bit into Magento's core code, I found that you need to use $item->getProduct()->setIsSuperMode(true)in order to make $item->setCustomPrice()and $item->setOriginalPrice()work.

在深入研究 Magento 的核心代码后,我发现您需要使用$item->getProduct()->setIsSuperMode(true)才能制作$item->setCustomPrice()$item->setOriginalPrice()工作。

Here is some sample code you can use within an Observer that listens for the checkout_cart_product_add_afteror checkout_cart_update_items_afterevents. The code is logically the same except checkout_cart_product_add_afteris called for only one item and checkout_cart_update_items_afteris called for all items in the cart. This code is separated/duplicated into 2 methods only as an example.

下面是一些示例代码,您可以在监听checkout_cart_product_add_aftercheckout_cart_update_items_after事件的观察者中使用。代码在逻辑上是相同的checkout_cart_product_add_after,只是只为一件商品checkout_cart_update_items_after调用,并为购物车中的所有商品调用。此代码仅作为示例被分离/复制为 2 个方法。

Event: checkout_cart_product_add_after

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

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

回答by Jonathan Day

Magento have changed the way the prices are calculated in the cart which makes it very difficult to do this in v1.4 onwards. If you do set the price using an Observer or other device, it will almost certainly be overwritten back to the catalog price.

Magento 改变了在购物车中计算价格的方式,这使得在 v1.4 之后很难做到这一点。如果您确实使用观察者或其他设备设置价格,它几乎肯定会被覆盖回目录价格。

Effectively, you need to use Shopping Cart rules to implement this.

实际上,您需要使用购物车规则来实现这一点。

回答by Simon

It is possible to set a customer specific price of a quote item. Hence, something like this should do it:

可以设置报价项目的客户特定价格。因此,应该这样做:

$quoteItem = $quote->addProduct($product, $qty);
$quoteItem->setCustomPrice($price);
// we need this since Magento 1.4
$quoteItem->setOriginalCustomPrice($price);
$quote->save();

Hope this helps...

希望这可以帮助...

回答by Deepak Bhatta

If I have to share my solution that I made on the base of Simon then I have managed to rewrite model class save function of quote.

如果我必须分享我在 Simon 的基础上制作的解决方案,那么我已经设法重写了引用的模型类保存功能。

public function save()
{

    $this->getQuote()->getBillingAddress();
    $this->getQuote()->getShippingAddress()->setCollectShippingRates(true);
    $this->getQuote()->collectTotals();
    //$this->getQuote()->save();

    foreach($this->getQuote()->getAllItems() as $item) {             
          $productId = $item->getProductId();
          $product = Mage::getModel('catalog/product')->load($productId);
          if($product->getAttributeText('is_dummy') == 'Yes') {
            $price = 2;
            $item->setCustomPrice($price);
            // we need this since Magento 1.4
            $item->setOriginalCustomPrice($price);
          }
    }  
       $this->getQuote()->save();   
    $this->getCheckoutSession()->setQuoteId($this->getQuote()->getId());
    /**
     * Cart save usually called after chenges with cart items.
     */
    Mage::dispatchEvent('checkout_cart_save_after', array('cart'=>$this));
    return $this;
}

回答by shaune

Jonathan's answer is likely the best for most situations. But some customers might not like how shopping cart discounts are displayed in the cart. I recently did a project (with Magento 1.3.3) where the customer didn't like how the each line item still showed the full price as well as the subtotal, with a Discount line below the subtotal - he wanted to see the price of each item discounted, and the subtotal show the discounted price as well. He reallydidn't like having the Discount line after the Subtotal line.

对于大多数情况,乔纳森的回答可能是最好的。但有些客户可能不喜欢购物车折扣在购物车中的显示方式。我最近做了一个项目(使用 Magento 1.3.3),客户不喜欢每个订单项仍然显示全价和小计的方式,小计下方有一条折扣线 - 他想看到每件商品都打折,小计也显示打折的价格。他真的不喜欢在小计行之后有折扣行。

Anyway, if you find yourself in the same boat, one approach is to override the getCalculationPrice() and getBaseCalculationPrice() methods in Mage_Sales_Model_Quote_Address_Item and Mage_Sales_Model_Quote_Item. I know that it isn't always pretty to override, much better to use events, but in this case I couldn't get events to work seamlessly on both the frontend and backend. Not sure if this approach will work in Magento 1.4+.

无论如何,如果您发现自己处于同一条船上,一种方法是覆盖 Mage_Sales_Model_Quote_Address_Item 和 Mage_Sales_Model_Quote_Item 中的 getCalculationPrice() 和 getBaseCalculationPrice() 方法。我知道重写并不总是很漂亮,使用事件要好得多,但在这种情况下,我无法让事件在前端和后端无缝工作。不确定这种方法是否适用于 Magento 1.4+。

回答by knowzero

I had the same issue and i am not a developer. What i did was added a new price attribute in magento backend called "site price". On the product page this showed the higher price $100. the actual price of the item was $90. so when the shopper adds it to cart they will see the actual price of the item, but on the product page they see the custom attribute price of $100

我有同样的问题,我不是开发人员。我所做的是在 magento 后端添加了一个新的价格属性,称为“站点价格”。在产品页面上,这显示了更高的价格 100 美元。该商品的实际价格为 90 美元。因此,当购物者将其添加到购物车时,他们会看到该商品的实际价格,但在产品页面上,他们会看到 100 美元的自定义属性价格

if all your prices on the product page are a set % higher then the real price just multiply your product price by the 1+percent. So if you want to add 10% to all your prices do price*1.1 This will display your price as 10% higher but when the shopper adds to cart they will see the real price.

如果您在产品页面上的所有价格都高出一定百分比,那么实际价格只需将您的产品价格乘以 1+%。因此,如果您想在所有价格上增加 10%,请执行 price*1.1 这将显示您的价格高出 10%,但当购物者添加到购物车时,他们将看到实际价格。