0

How To Create a script For Update Product SKU Using Custom Script.

0
  1. First create CSV and placed in the root folder (sku.csv) https://i.stack.imgur.com/HZrat.png

    1. Create a script in the root directory name script.php

      <?php 
      
      use Magento\Framework\App\Bootstrap;
      require __DIR__ . '/app/bootstrap.php';
      $bootstrap = Bootstrap::create(BP, $_SERVER);
      $objectManager = $bootstrap->getObjectManager();
      
      $state = $objectManager->get('\Magento\Framework\App\State');
      $state->setAreaCode('frontend');
      $fileCsv = $objectManager->get('Magento\Framework\File\Csv');
      $moduleReader = $objectManager->get('Magento\Framework\Module\Dir\Reader');
      $directoryList  = $objectManager->get('Magento\Framework\App\Filesystem\DirectoryList');
      $file = $objectManager->get('Magento\Framework\Filesystem\Io\File');
      
       $filePath = "sku.csv"; 
       if (file_exists($filePath)) {
          $rows = $fileCsv->getData($filePath);
          $count = 0;
          $successSku = [];
          $failedSku = [];
            foreach($rows as $row) {
              if($count > 0) {
                $oldSku  = (isset($row[0])) ? $row[0] : "";
                 $newSku  = (isset($row[1])) ? $row[1] : "";
           if($oldSku && $newSku) {
          $productId = $objectManager->create('Magento\Catalog\Model\Product')->getIdBySku($oldSku);
          if($productId) {
              try {
                  $productFactory = $objectManager->get('\Magento\Catalog\Model\ProductFactory');
                  $product = $productFactory->create()->load($productId);
                  $product->setSku($newSku);
                  $product->save();
                  $successSku[$newSku] = $newSku;
              }
              catch (\Exception $e) {
                  echo "Cannot retrieve products from Magento: ".$e->getMessage()."<br>"; 
              }
          }else {
              $failedSku[$oldSku] = $oldSku;  
               }
           }
         }
             $count++;
          }
         }
         echo "Sucessfully updated SKU";
      

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.