Firstly, we have to create a custom module.
Then, we have to declare a file named events.xml to catch an event that takes place after a product is added to the cart.
Create events.xml file at the following path Magemonkeys/CustomPriceInCart/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="CustomPriceInCart" instance="MagemonkeysCustomPriceInCartObserverCustomPriceInCart" /> </event> </config>
The next step is to create the observer to make changes to the price.
Create CustomPriceInCart.php file at the following path Magemonkeys/CustomPriceInCart/Observer/CustomPriceInCart.php
<?php
namespace MagemonkeysCustomPriceInCartObserver;
use MagentoFrameworkEventObserverInterface;
use MagentoFrameworkAppRequestInterface;
class CustomPriceInCart implements ObserverInterface
{
public function execute(MagentoFrameworkEventObserver $observer)
{
$item = $observer->getEvent()->getData('quote_item');
$item = ($item->getParentItem() ? $item->getParentItem() : $item);
// here your custom price goes
$customPrice = 101;
$item->setCustomPrice($customPrice);
$item->setOriginalCustomPrice($customPrice);
$item->getProduct()->setIsSuperMode(true);
}
}
By turning on super mode to the product through function setIsSuperMode(true), we can stop the system generating the price.
Then we can set the custom prices for products in the cart.


