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.

A Full Guide to Make Mac Environment for any…

Mac is Shipped with some predefined tools for US PHP – will Depreciated in next MacOS release Apache You can check with Install Http...
Shuvankar Paul
6 min read

Disable Magento 2 Two Factor Authentication

In new Magento Version by Default Magento 2 Enable Two Factor Authentication, but if you work on localhost, then it is not useful for...
Shuvankar Paul
12 sec read

Magento 2 Common Manual MySQL Query

Getting Number of Active Product in a Category
Shuvankar Paul
54 sec read

Leave a Reply

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