Please make sure the following things before running the script
- This script location is at root-folder/script
- System -> Configuration -> Catalog -> Catalog -> Frontend -> Use Flat Catalog Product should be No. If it is Yes then set it No first then execute the script and again you can set it Yes
- After execute the script reindex at System -> Index Management -> Product Flat Data
.
require_once('../app/Mage.php');
Mage::app();
$collection = Mage::getModel('catalog/product')->getCollection()
->addAttributeToSelect('*'); // select all attributes
$newPaths = array();
$normalizeChars = array(
'Š'=>'S', 'š'=>'s', 'Ð'=>'Dj','Ž'=>'Z', 'ž'=>'z', 'À'=>'A', 'Á'=>'A', 'Â'=>'A', 'Ã'=>'A', 'Ä'=>'A',
'Å'=>'A', 'Æ'=>'A', 'Ç'=>'C', 'È'=>'E', 'É'=>'E', 'Ê'=>'E', 'Ë'=>'E', 'Ì'=>'I', 'Í'=>'I', 'Î'=>'I',
'Ï'=>'I', 'Ñ'=>'N', 'Ń'=>'N', 'Ò'=>'O', 'Ó'=>'O', 'Ô'=>'O', 'Õ'=>'O', 'Ö'=>'O', 'Ø'=>'O', 'Ù'=>'U', 'Ú'=>'U',
'Û'=>'U', 'Ü'=>'U', 'Ý'=>'Y', 'Þ'=>'B', 'ß'=>'Ss','à'=>'a', 'á'=>'a', 'â'=>'a', 'ã'=>'a', 'ä'=>'a',
'å'=>'a', 'æ'=>'a', 'ç'=>'c', 'è'=>'e', 'é'=>'e', 'ê'=>'e', 'ë'=>'e', 'ì'=>'i', 'í'=>'i', 'î'=>'i',
'ï'=>'i', 'ð'=>'o', 'ñ'=>'n', 'ń'=>'n', 'ò'=>'o', 'ó'=>'o', 'ô'=>'o', 'õ'=>'o', 'ö'=>'o', 'ø'=>'o', 'ù'=>'u',
'ú'=>'u', 'û'=>'u', 'ü'=>'u', 'ý'=>'y', 'ý'=>'y', 'þ'=>'b', 'ÿ'=>'y', 'ƒ'=>'f',
'ă'=>'a', 'î'=>'i', 'â'=>'a', 'ș'=>'s', 'ț'=>'t', 'Ă'=>'A', 'Î'=>'I', 'Â'=>'A', 'Ș'=>'S', 'Ț'=>'T',
' '=>'-'
);
foreach ($collection as $productCollection) {
$product = mage::getModel('catalog/product')->load($productCollection->getId());
$images = $product->getMediaGallery('images');
foreach ($images as $image) {
$name = trim(strtolower($product->getName()));
$formattedName = preg_replace("/[^A-Za-z0-9\_\-\.]/", '', strtr($name, $normalizeChars));
$newPaths[$product->getSku()]['old'] = $image['file'];
$newPaths[$product->getSku()]['name'] = $name;
$newPaths[$product->getSku()]['formated'] = $formattedName;
$newPaths[$product->getSku()]['new'] = '/'.$formattedName[0].'/'.$formattedName[1].'/'.$newPaths[$product->getSku()]['formated'].'-'.$product->getSku().'.'.pathinfo($image['file'], PATHINFO_EXTENSION);
}
}
try {
$write = Mage::getSingleton('core/resource')->getConnection('core_write');
foreach ($newPaths as $newPath) {
copy('../media/catalog/product' . $newPath['old'], '../media/catalog/product' . $newPath['new']);
$query = 'UPDATE catalog_product_entity_media_gallery SET value = "' . $newPath['new'] . '" WHERE value ="' . $newPath['old'].'"';
$write->query($query);
$query = 'UPDATE catalog_product_entity_varchar SET value = "' . $newPath['new'] . '" WHERE value ="' . $newPath['old'].'"';
$write->query($query);
}
}catch (Exception $e){
var_dump($e);
}
var_dump($newPaths);