Shuvankar Paul Software Engineer, Strativ AB Magento eCommerce Website Development, Website Development Using Php and HTML and Cross-Platform application development using Appcelerator.

Bulk Replace Product SKU in Magento 2

55 sec read

The below code and content is tested in Magento 2.3.X

Sometimes you need to update the SKU in bulk process, but I will recommend not to do that, if there is no other way then do follow the step.

I will suggest doing that from external Script rather by Magento 2 Controller.

<?php

use Magento\Framework\App\Bootstrap;
use Magento\Framework\App\ObjectManager;

require __DIR__ . '/../../app/bootstrap.php'; // as i use Script/BulkSKU that's the reason i load it from two up document

$params = $_SERVER;
$bootstrap = Bootstrap::create(BP, $params);
$obj = $bootstrap->getObjectManager();

$state = $obj->get('Magento\Framework\App\State');
$state->setAreaCode('adminhtml'); // or you can use frontend

$objectManager = ObjectManager::getInstance();

$dataArray = array(
    "OLD_SKU_1" => "NEW_SKU_1",
    "OLD_SKU_2" => "NEW_SKU_2",
    "OLD_SKU_3" => "NEW_SKU_3",
    "OLD_SKU_4" => "NEW_SKU_4"
);

foreach ($dataArray as $key=>$value){
    //-- Getting Product Data
    $_product = $objectManager->create('\Magento\Catalog\Model\Product')->loadByAttribute('sku', $key);
    try {
        if ($_product) {
            $_product->setSku($value)->save();
            echo "Successful ---- Old : $key ---- New : $value<br>";
        } else {
            echo "Item Not Found ---- Old : $key ---- New : $value<br>";
        }
    }
    catch (\Exception $e) {
        echo "Cannot retrieve products from Magento: ".$e->getMessage()."<br>";
        continue;
    }
}

As this is bulk process php timeout can happen if your execution time is not so high or it manages from user.ini or PHP index.php file or .htaccess

Add following line top of your PHP script

ini_set('max_execution_time', '1000'); // execution time accorading to your amount of products

Download Full Complete Code

Click Here — Google Drive Link

Shuvankar Paul Software Engineer, Strativ AB Magento eCommerce Website Development, Website Development Using Php and HTML and Cross-Platform application development using Appcelerator.

Setting Up Magento 2 minimal & optimize environment in…

Setting Up Magento 2 minimal & optimize environment in Ubuntu including PHP, MySQL, PhpMyAdmin, PHP Extension, Composer, Folder Permission & Users
Shuvankar Paul
3 sec read

Leave a Reply

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