In the vast realm of e-commerce, Magento stands out as a powerful platform, offering developers the flexibility to shape functionalities according to their preferences.
This guide outlines the steps to set a custom price of the product programmatically when adding a product to the cart in Magento 2.
The ability to set a custom price on this platform can be a game-changer for online store owners seeking to implement strategic pricing strategies.
Whether it's a promotional discount, a special offer, or a dynamic pricing model, the flexibility offered by Magento 2 empowers businesses to tailor their pricing to meet specific needs.
The Magento 2 custom price extension by MageAnts allows an admin to set a custom price of a particular product from the backend.
The custom price will be not visible to the customers, so customers need to ask a fair price of the product.
Steps to Add Product to Cart With Custom Price in Magento 2 Programmatically
There are various methods to set a custom price of the product when adding the product to the cart, and in this guide, we'll explore the observer method.
Creating an Observer:Begin by creating an events.xml file in the etc directory:
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<event name="checkout_cart_product_add_after">
<observer name="custompricing_addtocart_observer"
instance="Blog\CustomCart\Observer\AddToCart"/>
</event>
</config>
|
|
Now, create the Observer file in the Observer directory:
<?php>
namespace Vendor\CustomCart\Observer;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
class AddToCart implements ObserverInterface
{
public function execute(Observer $observer)
{
$item = $observer->getEvent()->getData('quote_item');
$item = ($item->getParentItem() ? $item->getParentItem():$item);
// Set your custom price logic here
$customPrice = 19.99; //Replace with your custom price
// Set the custom price
$item->setCustomPrice($customPrice);
$item->setOriginalCustomPrice($customPrice);
$item->getProduct()->setIsSuperMode(true);
}
}
?>
|
With these configurations, the observer is now ready to listen to the checkout_cart_product_add_after event and execute the custom logic when adding products to the cart.
Conclusion
Adding products to the cart with custom prices programmatically in Magento 2 empowers merchants to tailor their offerings, creating a more personalized and engaging shopping experience for customers.
Checkout our Magento extension development services to improve performance and security of your online store.