How to set a custom price programmatically when adding a product to the cart in Magento 2?

In this article, you will be learning how to set a custom price for product programmatically when adding a product to the cart in magento 2.

Here we are using Aureatelabs as Vendor name and CustomPrice as the name of module.  You can change this according to your Vendor and Module name

The first thing you need to do is to  create an events.xml file in the app/code/Aureatelabs/CustomPrice/etc/frontend folder

<?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="Aureatelabs\CustomPrice\Observer\CustomPrice" />
	</event>
</config>

Here we are using checkout_cart_product_add_after event which will be called after adding a product to the cart.

Now we need to create an Observer as defined in the event.xml file

So we need to create a CustomPrice.php file in the app/code/Aureatelabs/CustomPrice/Observer folder

<?php

namespace Aureatelabs\CustomPrice\Observer;

use \Magento\Framework\Event\ObserverInterface;

/**
 * Class CustomPrice
 * @package Aureatelabs\CustomPrice\Observer
 *
 */
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 );

		//Define your Custom price here
		$price = 100;
	 
		//Set custom price
		$item->setCustomPrice($price);
		$item->setOriginalCustomPrice($price);
		$item->getProduct()->setIsSuperMode(true);
	}
}
  • Share :