How to set a custom price after Add Product

Sometimes for some reason, you have to change a product price on the fly when a customer add a product to the basket.
We are going to see how we can achieve that.

We are going to use an event : checkout_cart_product_add_after

Create a file events.xml like that MyNamespace/MyModule/etc/events.xml

<config xmlns:xsi="" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="checkout_cart_product_add_after">
        <observer name="set_custom_price" instance="MyNamespace\MyModule\Observer\SetCustomPriceAfterAddProduct" />

Now we have to create our Observer 🙂


namespace MyNamespace\MyModule\Observer;

use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;

class SetCustomPriceAfterAddProduct implements ObserverInterface
     * @event checkout_cart_product_add_after
     * @param Observer $observer
     * @throws \Magento\Framework\Exception\NoSuchEntityException
    public function execute(Observer $observer)
        /** @var \Magento\Quote\Model\Quote\Item $item */
        $item = $observer->getEvent()->getData('quote_item');
        $item = ($item->getParentItem() ? $item->getParentItem() : $item);
        $price = 100;

and voila ! You have change the item price 🙂

Name (required)Email (required)Website

Leave a Reply