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.