Reading list Switch to dark mode

    Magento2 – Set custom price of Product when adding to cart

    Updated 16 July 2021

    Here we will see how to set custom price of product in magento2.
    You can change product price when adding product to cart. You can achieve this by Observer.

    learn here how to create observer in Magento2.

    Set Custom Price of Product

    First create events.xml file in 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>

    Now create CustomPrice.php file in 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);
    		}
    
    	}

    Searching for an experienced
    Magento 2 Company ?
    Find out More
    . . .

    Leave a Comment

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


    11 comments

  • Abhishek Panchal
  • Ashish
    • Webkul Support
  • nagaraju
  • Manish Saini
  • tallenmusclegeeks
  • Felipe
    • nagaraju
      • Felipe Marques
        • nagaraju
  • Valentin Picui
  • Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home