X
    Categories: Knowledgebase

How to change product price by code for magento

Magento 1 :

The code for change price of product, you can put on controller, model, helper or any where

//load product by id
$product = Mage::getModel('catalog/product')->load($productId);
//change base price
if($product->getId()){
    //increase base price + 5
    $newPrice = $product->getPrice()+5;
    $product->setPrice($newPrice);
    $product->save();
}
//change special price
if($product->getSpecialPrice()){
    //increase special price + 5
    $newPrice = $product->getSpecialPrice()+5;
    $product->setSpecialPrice($newPrice);
    $product->save();
}

Magento 2 :

To change price of product you need to follow these functions:

//instance of object manager 
$objectManager = MagentoFrameworkAppObjectManager::getInstance();
//create product model via object manager
$product = $objectManager->create('MagentoCatalogModelProduct');
//load product by id
$product->load($productId)
//change base price
if($product->getId()){
    //increase base price + 5
    $newPrice = $product->getPrice()+5;
    $product->setPrice($newPrice);
    $product->save();
}
//change special price
if($product->getSpecialPrice()){
    //increase special price + 5
    $newPrice = $product->getSpecialPrice()+5;
    $product->setSpecialPrice($newPrice);
    $product->save();
}

Thank for reading this post, Hope it helps.

Kien Wiliam: Magento Ecommerce Developer