0
votes

After exporting, changing some details and then importing a large number of products into Magento, I noticed all the images are no longer set. The images still exist in the media gallery for each product, but they are not set as the base image.

I've seen that in some cases, you need to copy images over to a /media/import/ folder, but is it possible to change the import file so that I can keep the images where they are?

Right now, all the images appear to be in a folder: /media/catalog/product/

Any help would be very appreciated.

Additionally, if it were possible to run a script that sets all product's base image to the first image in its gallery, that would work just as well. Thanks!

1

1 Answers

1
votes

Let's say that you have load the products and you are ready to make a change and save them. With this code:

if (file_exists($imagePath)) {//New image file
 //Load your media table
 $mediaApi = Mage::getModel("catalog/product_attribute_media_api");
 try {
 //Now you have all the images available for your product 
 //if you previously have assign anything
  $items = $mediaApi->items($product->getId());
 //loop them
      foreach ($items as $item) {
 //With that line you can remove them if you want
 echo ($mediaApi->remove($product->getId(), $item['file']));
             }
   } catch (Exception $exception) {
           var_dump($exception);
    die('Exception Thrown');
    }

 $cache = Mage::getSingleton('core/cache');
 $cache->flush();
//You need that line
$product->setMediaGallery(array('images' => array(), 'values' => array()));
//That line assigns your new image.As base,thumbail and image.
//Use it in the loop if you want to reassign an existing image.
$product->addImageToMediaGallery($imagePath, array('thumbnail', 'small_image', 'image'), false, false);

I hope that helps you Cheers!