Magento – Programmatically rename product images–existing images already uploaded–for SEO

magento-1.9product-imagesprogrammaticallyseo

I would like to create a simple script to programmatically rename existing, already uploaded product images (without having to re-upload them or use the admin backend).

To process this in manageable chunks, I'm thinking something along the lines of:

  1. specify a category ID, get product collection
  2. foreach product, get all product images
  3. foreach image, rename file on server, update database table(s), following naming convention:
$new_img_name = 'company-name-' . strtolower(preg_replace("/\W+/m", "-", $_product->getName())) . '-' . $product_image_number_incremental;

Steps 1 and 2 above I can do, but I'm not having any luck changing the actual file name on the server and in the database—I can only seem to find programmatic ways to change things like image label.

Thoughts?

Details:

  • Magento CE 1.9.1.1
  • approx. 900 products
  • approx. 10 images per product

Reasoning:

  • I'd like our product images to follow a more SEO-friendly naming convention that includes our company name, the product name, and style information—preferably without all the manual labor of downloading, renaming, and re-uploading all product images (there are a lot…)

Best Answer

Please make sure the following things before running the script

  1. This script location is at root-folder/script
  2. 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
  3. 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);
Related Topic