How to Add Product To Cart With Custom Price in Magento 2

With the support of seamless customization and integrations, Magento 2 e-commerce stores can serve excellent experiences to customers. In many cases, the store owners are willing to allow the shoppers to add the product to the cart with a custom price.

Frequently, the store owner is prepared to set a fixed product pricing even if the consumer selects various options/add-ons from the front end for all or some specific products. Instead of manually changing all store products, we’ll need to manually code to override all store product prices with your preferred custom price.

In this article, I will instruct you to set a custom price of the product when adding the product to the cart by using Observe.

Let’s explore two straightforward steps below!

Step 1: Create Events/xml File

Firstly, you need to create events/xml in the folder Mageplaza/HelloWord/etc/frontend and use event checkout_cart_product_add_after

<?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="customprice" instance="Mageplaza\HelloWord\Observer\CustomPrice" />
    </event>
</config>

Step 2: Create CustomPrice.php File

Now, you have to create CustomPrice.php file that overrides your price in the Observer Folder.

<?php
    /**
     * Mageplaza Hello CustomPrice Observer
     *
     * @category    Mageplaza
     * @package    Mageplaza_HelloWord
     *
     */
    namespace Mageplaza\HelloWord\Observer;
 
    use Magento\Framework\Event\ObserverInterface;
    use Magento\Framework\App\RequestInterface;
 
    class CustomPrice implements ObserverInterface
    {
        public function execute(\Magento\Framework\Event\Observer $observer) {
            $item = $observer->getEvent()->getData('quote_item');         
            $item = ( $item->getParentItem() ? $item->getParentItem() : $item );
            $price = 100; //set your price here
            $item->setCustomPrice($price);
            $item->setOriginalCustomPrice($price);
            $item->getProduct()->setIsSuperMode(true);
        }
 
    }

Note: According to your need for setting a custom price for one or more products, you can manipulate this by adding conditions.

Conclusion

That is the detailed instruction on how to add the product to the cart with the custom price in Magento 2. Let us know if you have any questions by commenting below!

Image Description
Hello, I'm the Chief Technology Officer of Mageplaza, and I am thrilled to share my story with you. My deep love and passion for technology have fueled my journey as a professional coder and an ultra-marathon runner. Over the past decade, I have accumulated extensive experience and honed my expertise in PHP development.
x