How to Update Product Price Programmatically in Magento 2
After you have successfully created a store, created categories, added products in Magento 2, set up initial prices, and voila!, you are ready to market them and wait for the sales!
You priced the products choosing a strategy but selecting a optimal price strategy is a difficult task. There are many factors affecting the product prices, some of them being:
- Fluctuation in market
- Arrival of new competitors
- Change in demand
- Inflation
- Increased production cost, and many more
Product price updation is an ongoing process. You cannot pick a strategy, set a price, leave it and expecting to be profitable, and thus, you may require to update the product prices.
Manually updating the product prices from the admin is tiresome and time consuming task. Rather, you should update product price programmatically in Magento 2 to quicken up the process. You can also update currency rates automatically which will save your time rather than doing it manually.
Here I’ve come up with the solution to update product price programmatically in Magento 2.
Steps to Update Product Price Programmatically in Magento 2
Use the below code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $productId = 1; $price = 100; $store = 1; $product = $objectManager->create('Magento\Catalog\Model\Product')->load($productId); try { $product->setStoreId($store); $product->setPrice($price); $product->save(); } catch (\Exception $e) { echo "Error Id : " . $productId; } |
This code will automatically update the price of a product with Id 1. setPrice function plays a vital role in updating the price.
Simple,,, Right?
If you have any doubts, just mention them in the Comments section below.
I would be happy to help.
Feel free to share the solution with Magento 2 community via social media.
Thank You.
Sanjay Jethva
Sanjay is the co-founder and CTO of Meetanshi with hands-on expertise with Magento since 2011. He specializes in complex development, integrations, extensions, and customizations. Sanjay is one the top 50 contributor to the Magento community and is recognized by Adobe.
His passion for Magento 2 and Shopify solutions has made him a trusted source for businesses seeking to optimize their online stores. He loves sharing technical solutions related to Magento 2 & Shopify.
4 Comments
hello sir how to increase product length in change product price
Hello Ganga ram,
The above blog is for updatting the product price only.
Thank You
where exactly shall i write and save the above piece of code?
Hello,
You can use the above code wherever you want, for instance, you can use it in the helper, model, or controller file.
Thank You.