Magento 2 Add Product To Cart With Custom Price
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 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 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 Webkul/Hello/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="Webkul\Hello\Observer\CustomPrice" />
</event>
</config>
Step 2: Create CustomPrice.php File
Now, you have to create CustomPrice.php
file that override your price in the Observer
Folder.
<?php
/**
* Webkul Hello CustomPrice Observer
*
* @category Webkul
* @package Webkul_Hello
* @author Webkul Software Private Limited
*
*/
namespace Webkul\Hello\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
Above is the details instruction of how to add the product to cart with the custom price in Magento 2. Let us know if you have any questions by commenting below!
Enjoyed the tutorial? Spread it to your friends!