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="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" instance="MyNamespace\MyModule\Observer\SetCustomPriceAfterAddProduct" />
    </event>
</config>

Now we have to create our Observer 🙂

<?php

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;
        $item->setOriginalCustomPrice($price);
        $item->getProduct()->setIsSuperMode(true);
    }
}

and voila ! You have change the item price 🙂

Name (required)Email (required)Website

Leave a Reply