Magento 2 Cart – Add Product to Cart with Price 0 When Same Product in Cart

magento2

I'm trying add to cart a item with price 0 when I have this product added in the cart.

Example: I have in the cart the product with SKU: 0000123 with his current price: 2.00 with a new functionality of my web and now I want add the SKU: 0000123 with the price 0 but when i try add again with price 0 only modify the qty of the 1st item to 2

I have an Observer with the event checkout_cart_product_add_after

Question: How can I add the simple product with price 0 when i have the same product in the cart with his real price?

Best Answer

  1. create events.xml on the following location.

app\code\Vendor\Extension\etc\frontend\events.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="checkout_cart_product_add_after">
            <observer name="set_custom_price_after_add_to_cart" instance="Vendor\Extension\Observer\Customprice" />
    </event>
</config>
  1. create Customprice.php on following location.

app\code\Vendor\Extension\Observer\Customprice.php

<?php

namespace Vendor\Extension\Observer;

use \Magento\Framework\Event\ObserverInterface;

class Customprice implements ObserverInterface
{
    public function execute(\Magento\Framework\Event\Observer $observer) {
        $item = $observer->getEvent()->getData('quote_item');

        // Get parent product if current product is child product
        $item = ($item->getParentItem()?$item->getParentItem():$item);

        //HERE YOU NEED TO CHECK IF PRODUCT EXIST INTO CART, THEN CHANGE PRICE OTHERWISE NOT.

        $price = 0; //Set Custom Price Here

        //Set custom price
        $item->setCustomPrice($price);
        $item->setOriginalCustomPrice($price);
        $item->getProduct()->setIsSuperMode(true);
    }
}