HummingbirdUK main logo

Coding solutions to business problems

About us

We use code to create solutions to business challenges, bottle-necks and headaches.

If you think your business has a problem that can be solved through code, we are happy to chat things through without any obligation.

Get in touch

How to change SKUs in bulk in Magento

Home / Blog / How to change SKUs in bulk in Magento

Written by Giles Bennett

A client dropped us a line the other day looking to change the SKUs on all of their products. Whilst most things can be changed in bulk using Magento's import / export functionality, a product's SKU isn't one of them, because that functionality uses the SKU to identify the product - so you can't go changing it mid-import.

It can still be done pretty quickly, though, using a small script and a CSV. The CSV just needs to contain two columns, and no headers - the first column should be the existing product SKU, and the second column should be the SKU you want it to change to.

The script looks as follows. First we hook into Magento in the usual way (this assumes that you're putting the CSV and the script in the web root of your Magento installation) :

require_once 'app/Mage.php';
umask(0);
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);

Upload the CSV as a file called 'skus.csv' in the same location, then the script can access it and loop through it :

if (($handle = fopen("skus.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {

Then it gets the old SKU and the new SKU into variables :

$oldsku = $data[0];
$newsku = $data[1];

It tries to load the product associated with the old SKU, and if the product exists...

$product = Mage::getModel('catalog/product')->loadByAttribute('sku', $oldsku);
if($product) { 

...it sets the SKU to be the new SKU, saves the product, outputs confirmation, and moves on :

$product->setSku($newsku);
$product->save();
echo  $product->getName() . ' SKU updated';
echo "\n";
}
}
}
?>

And that's it. Hit the file in a browser, or over SSH, and you're away.

Author : Giles Bennett

About the author

Giles Bennett built his first website in 1996, and is old enough to miss Netscape Navigator. Initially a lawyer, he jumped ship to IT in 2008, and after 5 years as a freelancer, he founded HummingbirdUK in 2013. He can be reached by email at giles@hummingbirduk.com.