I have a bunch of images of the products for my shop. Now, i don't want to add all the images one by one because it would be very time consuming. The images' file names are equal to the product name, so I tried this:
<?php
require_once('app/Mage.php');
umask(0);
Mage::app('default');
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
$importDir = Mage::getBaseDir('media') . DS . 'import/';
$_productCollection = Mage::getModel('catalog/product')
->getCollection()->addAttributeToSelect('*');
foreach($_productCollection as $_product)
{ $fileName = $_product->getName();
$filePath = $importDir.$fileName;
if ( file_exists($filePath) ) {
try {
$_product->addImageToMediaGallery($filePath, 'image', false, false);
$_product->addImageToMediaGallery($filePath, 'small_image', false, true);
} catch (Exception $e) {
echo $e->getMessage();
}
}
$_product->save();
}
?>
The code itself would work if I would take one specific image, but it does not work with the name. All the images are inside the import folder.
Thanks!