Magento 2 add product to cart with custom price is very necessary for developer when building Magento extensions or doing projects in magento 2 because some time you want to custom price for separate Products .
In order to add product to cart with custom price, You have to do 3 tasks :
– Create Simple Extension
– Declare event
– Create function Custom Price
1. Create Simple Extension
In order to add product to cart with custom price, you should use extension to do that because you can enable ,disable , remove or use for other website. you can check more Magento 2 how to custom module to create new module .
2. Declare event
In order declare event , you will push code to app/code/Vendor/ModuleName/etc/evetns.xml , you can check more detail how to use event in this post.
<?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="{eventName}"> <observer name="{CustomEventName}" instance="Vendor\ModuleName\Observer\Actions" /> </event> </config>
For my example , We will create event like that
<?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="magebay_custom_price" instance="Magebay\Hello\Observer\CustomPrice" /> </event> </config>
3. Create function Custom Price
As you can see, I define function in Magebay/Hello/Observer/CustomPrice show now I will create function custom price
Magebay/Hello/Observer/CustomPrice
<?php /** * Created by PhpStorm. * User: maiuoc * Date: 2019-02-12 * Time: 8:26 AM */ namespace Magebay\Hello\Observer; use Magento\Framework\Event\Observer as EventObserver; use Magento\Framework\Event\ObserverInterface; class CustomPrice implements ObserverInterface { function execute(EventObserver $observer) { /** @var \Magento\Quote\Model\Quote\Item $item*/ $item = $observer->getData('quote_item'); $item = ($item->getParentItem() ? $item->getParentItem() : $item); /** @var \Magento\Catalog\Model\Product $_product*/ $_product = $observer->getEvent()->getData('product'); $customPrice = $_product->getFinalPrice() + 10; // custom price $item->setCustomPrice($customPrice); $item->setOriginalCustomPrice($customPrice); // Enable super mode on the product. $item->getProduct()->setIsSuperMode(true); } }
Clear Cache and add product to cart , you will price will be changed .
As you can see, We can create a lot of custom function in magneto , We are having a lot of great extensions like Booking System Pro, Online product designer… that use a lot of custom functions, you if have any ideas about custom separate products , you can contact with us. We can check and do the tasks for you.