Magento Custom Development Development is a must for any business to fulfill their needs and save time and efforts by serving excellent shopping experience to your shoppers. Whether it is frontend or backend, Magento supports seamless customization & integrations to fulfill every business needs.
Several times, it happens that the store owner is willing to set a fixed product price even if multiple options/add-ons are selected by the customer from the frontend for all or some specific products. At that time we need to manually code to override all store product price with your desired custom price instead of manually editing all store products.
Here is a small piece of code that allows you to do the same.
First create file “events.xml” file at below Path.
app\code\Vendor\Extension\etc\frontend\events.xml
1 2 3 4 5 6 | <?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="Vendor\Extension\Observer\Customprice" /> </event> </config> |
Now we need one more file named “Customprice.php” that override our price using below code.
app\code\Vendor\Extension\Observer\Customprice.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <?php namespace Vendor\Extension\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); } } |
That’s it! You are free to play and manipulate this according to your need for setting a custom price for one or more products by adding conditions.
Let us know if you are facing an issue while implementing using this code by commenting below.
Happy Coding!
Hi, This is a nice tutorial. If you can suggest me, suppose i have different tier price (which is different than Magento product tier price added in backend) for a specific product. Then how can I achieve the same?