Update magento 2 price

This tutorial explains how to update Magento 2 price programmatically. Here I am updating the Magento 2 price from CSV.

Update magento 2 price

function updatePrice($objectManager,$productDatas) {

    $allData = array();

    foreach ($productDatas as $productData) {

        try {

            $productRelatedExist = $objectManager->get('\Magento\Catalog\Model\ProductRepository')->get(trim($productData[0]));

            if(!is_null($productRelatedExist)) {

                if(isset($productData[13])) {

                    $allData[$productData[0]] = array($productData[0],$productRelatedExist->getPrice(),$productData[13]);
                    echo 'Sku : ' . $productData[0] . ' Old Price : ' . $productRelatedExist->getPrice() . ' __ ' . ' New Price : ' . $productData[13] . PHP_EOL;
                    $productRelatedExist->setPrice($productData[13]);
                    echo 'Updated Price : ' . $productRelatedExist->getPrice() . PHP_EOL;
                    echo '--------------------------------------------------------------------' . PHP_EOL;
                    $productRelatedExist->save();

                }
                else {

                    echo 'Price not set : ' . $productData[0] . PHP_EOL;
                }

            }


        }
        catch(Exception $e)
        {
            echo 'Product Sku not existing : '. $productData[0].PHP_EOL;
        }

    }

    $sampleheaders = ['sku','Old Price','New Price'];
    createCSV( $allData, 'price_update.csv', $sampleheaders);

}

Update log

function createCSV( $data , $fileName, $headers ) {


    $file = fopen($fileName, 'w');
    fputcsv($file, $headers);

    foreach ($data as $row) {

        fputcsv($file, $row);

    }
    fclose($file);

}

Share this Tutorial

Leave a Reply

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

*