0

How to add product to cart with price 0. It is something like an free product add to cart programmatic ally without any cart rule?

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

        $price = 32; //Set Custom Price Here
     
        //Set custom price
        $item->setCustomPrice($price);
        $item->setOriginalCustomPrice($price);
        $item->getProduct()->setIsSuperMode(true);
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.