Set custom price of product before adding it to cart in Magento 2

This post will demonstrate that how Set custom price of product before adding it to cart in Magento 2.
First of all you need to create events.xml file in Vendor\Module\etc\frontend\ path. In events.xml file you have to call “checkout_cart_product_add_after” event to perform any action after product added to cart.

[php]
<?xml version=”1.0″?>
<config xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221; xsi:noNamespaceSchemaLocation=”urn:magento:framework:Event/etc/events.xsd”>
<event name=”checkout_cart_product_add_after”>
<observer name=”customprice” instance=”Vendor\Module\Observer\CustomPrice” />
</event>
</config>
[/php]

After that you need to create CustomPrice.php observer file under Vendor\Module\Observer path. This file is responsible for changing anything for product you want.

 

[php]
<?php namespace Vendor\module\Observer; class CustomPrice implements ObserverInterface { public function execute(\Magento\Framework\Event\Observer $observer) { $product_id = $observer->getProduct()->getId();
$custom_price = 20.0000
$item = $observer->getEvent()->getData(‘quote_item’);
$item = ( $item->getParentItem() ? $item->getParentItem() : $item );
$item->setCustomPrice($product_price);
$item->setOriginalCustomPrice($product_price);
$item->getProduct()->setIsSuperMode(true);
}
[/php]

That’s all. After saving your file. Run “php bin/magento setup:upgrade” on your magento root via command line.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.