Magento – Fixing Duplicate Images Issue in Media Gallery

mediaproduct-images

So I have a folder of images and a php array that has sku's for keys and an array of images i need to add to that sku's gallery as its value …for example:

['A2052'] => ['tmp/A2052-1.jpg', 'tmp/A2052-2.jpg']

I run through this array and try to add the images to the products with this code:

    foreach ($skuImageMap as $sku => $images) {
        $ourProduct = Mage::getModel('catalog/product')->loadByAttribute('sku', $sku);
        if ($ourProduct) {
            foreach ($images as $index => $imagePath) {
                if (file_exists($imagePath)) {
                    try {
                        $ourProduct->addImageToMediaGallery($imagePath, null, false, false);
                        $ourProduct->save();
                        echo "The image $imagePath was added to $sku successfully : $imageCount \n";
                        $imageCount++;
                    } catch (Exception $e) {
                        echo "There was an issue saving image $imagePath to $sku :" . $e->getMessage() . "\n";
                    }
                } else {
                    echo "The image $imagePath does not exist.\n";
                }
            }
        } else {
            echo "The product $sku does not exist \n";
        }
    }

The issue is that when I run this script I get two images saved to the gallery for each image. One correct one and another with _1 appended (which obviously doesnt exist so its broken). I can't seem to stop this duplication. Why is it adding two images on every save?

Best Answer

Most likely its because you are saving the product after every addImagetoMediaGallery moving it out of the loop of both images should suffice.

Untested but like this perhaps?

foreach ($skuImageMap as $sku => $images) {
    $ourProduct = Mage::getModel('catalog/product')->loadByAttribute('sku', $sku);
    $saveFlag = true;
    if ($ourProduct) {
        foreach ($images as $index => $imagePath) {
            if (file_exists($imagePath)) {
                try {
                    $ourProduct->addImageToMediaGallery($imagePath, null, false, false);
                    $imageCount++;
                } catch (Exception $e) {
                    $saveFlag = false;
                    echo "There was an issue saving image $imagePath to $sku :" . $e->getMessage() . "\n";
                }
            } else {
                $saveFlag = false;
                echo "The image $imagePath does not exist.\n";
            }
        }

        if($saveFlag) {
            try {
                $ourProduct->save();
                echo "The image $imagePath was added to $sku successfully : $imageCount \n";
            } catch (Exception $e) {
                zend_debug::dump($e->getMessage());
            }
        }

    } else {
        echo "The product $sku does not exist \n";
    }
}
Related Topic