Blog

How to set custom Price for Products in Cart in Magento 2

Magento supports a variety of integrated customization where you are capable of setting the custom price for products in the cart, for instance. Instead of manually editing each store product, the solution we’re heading at is implementing a short snippet of code to your module to override all store products’ prices with your desired one.

Pricing in Magento2:

For displaying product prices on product pages or widgets, Magento calculates the lowest price from one of the base price, special price, tier price, or catalog rule price. Configurable products can set their own prices for child products and bundle products can apply a fixed price on the bundle. Then when adding the product to the cart its price can be affected by cart price rules too.

In this article, we will show how to add your custom price to a product in the cart. This action will be overriding the price Magento has calculated.

Custom price for products in the cart

In order to add product to cart with custom price, You have to do last 2 steps if you have already module created. I will explain right from scratch to accomplish this tasks :

  1. Create Simple Extension
  2. Declaration of Module
  3. Registration of Module
  4. Activate the Module
  5. Declare event
  6. Create Observer with the code for setting Custom Price

So let’s start,

Step 1: Create Simple Extension

Create the following folders in the magento project root directory (ex. – C:\xampp\htdocs\magento2):

  • app/code/Thecoachsmb
  • app/code/Thecoachsmb/Customprice

The Thecoachsmb folder is the module’s VendorName, and Customprice is the ModuleName.

Note: If you don’t have the code folder in your app directory, create it manually.

Step 2: Declaration of Module

It is necessary to create etc folder and add the module.xml file in it

  app/code/Thecoachsmb/Customprice/etc/module.xml

Contents would be:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="Thecoachsmb_Customprice" > 
 </module> 
</config>

Step 3: Registration of Module

To register the module, create a registration.php file in the app/code/Thecoachsmb/Customprice/registration.php

Contents would be:

<?php
\Magento\Framework\Component\ComponentRegistrar::register(
	\Magento\Framework\Component\ComponentRegistrar::MODULE,
	'Thecoachsmb_Customprice',
	__DIR__
);

Step 4: Activate the Module

Now its time to enable our moule. Lets check the status of our module by typing below command in the magento project root directory (ex. – C:\xampp\htdocs\magento2) as: – after enabling the module first time, so you have to upgrade the database of the module by using this command line:

php bin/magento module:enable Thecoachsmb_Customprice && php bin/magento setup:upgrade 
&& php bin/magento setup:static-content:deploy -f

Step 5: Declare event

Firstly, after having your custom module installed, you declare a file named events.xml to catch an event that takes place after a product is added to the cart.

File Location : app/code/Thecoachsmb/Customprice/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="Thecoachsmb\Customprice\Observer\CustomPrice" />
	</event>
</config>

Here you declare an observer named customPriceInCart that will handle the event checkout_cart_product_add_after which Magento dispatches every time a product’s added to the cart.

Step 6: Create Observer for Custom Price

Next up, we create the observer class: app/code/Thecoachsmb/Customprice/Observer/CustomPrice.php

<?php
namespace Thecoachsmb\Customprice\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\App\RequestInterface;

class CustomPrice implements ObserverInterface
{
	public function execute(\Magento\Framework\Event\Observer $observer)
	{
		//get the item just added to cart
		$item = $observer->getEvent()->getData('quote_item');
                $product = $observer->getEvent()->getData('product');
		//(optional) get the parent item, if exists
		$item = ($item->getParentItem() ? $item->getParentItem() : $item);
		// set your custom price
		$price = 100;
                $item->setCustomPrice($price);
                $item->setOriginalCustomPrice($price);
                $item->getProduct()->setIsSuperMode(true);
	}
}

By turning on super mode to the product through function setIsSuperMode(true), you stop the system generating the price then set your custom one instead.

Clear cache by php bin/magento c:f  and check the functionality.

Implementation Logic:

Understand the Logic where I am also talking about tables used qoute and quote_item for saving custom price for product and also about the different conditions we can apply, watch below video

Conclusion:

The tutorial has explained how to set custom price of products when they appear in the cart of customers. Aside from setting a fixed number, you can add your own functions and inject other classes into the observer for custom pricing logics.

Thank you for reading the article. Please let us know your feedback on this article. We will love to hear back from you.

Leave a Reply

Your email address will not be published. Required fields are marked *

🚀 Let’s Connect on LinkedIn! 🚀

Want to level up your skills and knowledge? 🚀
Follow us on LinkedIn to get:
✅ Expert insights on business growth
✅ Daily tips to sharpen your skills
✅ Exclusive updates from The Coach SMB

Let's grow together!