How to Add Product To Cart With Custom Price in Magento 2

Steps to Add Product To Cart With Custom Price in Magento 2

Step 1: First, create a file “events.xml” at the below-given path.

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

Now add the below code

Step 2: Now, we need one more file named “Customprice.php” that overrides our price. Go to the below path

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

And finally, add the code as mentioned below,

<?php namespace Vendor\Extension\Observer;

use Magento\Framework\Event\ObserverInterface;

use Magento\Framework\App\RequestInterface;

class Customprice implements ObserverInterface {

public function execute(\Magento\Framework\Event\Observer $observer) {

$item =$observer->getEvent()->getData(‘quote_item’);

$item =($item->getParentItem() ? $item->getParentItem() : $item );

$price =100; //set your price here

$item->setCustomPrice($price);

$item->setOriginalCustomPrice($price);

$item->getProduct()->setIsSuperMode(true);

}
}

Leave a comment

Your email address will not be published. Required fields are marked *