Chapters Close

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

Being the responsible Magento eCommerce development agency, we’re determined to solve your basic custom pricing queries. In this article, you will be learning how to set a custom price for a 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);
	}
}

Related Sources

  1. How to use Magento 2 custom price renderer
  2. Convert price to current currency in Magento 2
  3. How to Add Custom Validation Rule in Magento 2?
Speak your Mind

Post a Comment

Got a question? Have a feedback? Please feel free to leave your ideas, opinions, and questions in the comments section of our post! ❤️

* This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

Grow your online business like 4,169 subscribers

    * This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.
    envelope

    Thank You!

    We are reviewing your submission, and will be in touch shortly.