I want to copy the images of a product to another product. I wrote the following script:

$mediaGallery = $anotherProduct->getMediaGallery();


foreach($mediaGallery["images"] as $image) {
    $filePath = $importDir.$image["file"];
    if(file_exists($filePath) && !file_exists(Mage::getBaseDir('media').DS.'import'.DS.'catalog'.DS.'product'.$image["file"])) {

        $p->setStoreId(Mage_Core_Model_App::ADMIN_STORE_ID)->addImageToMediaGallery($filePath, array('small_image','thumbnail','image'), false, false)->save();

        $attributes = $p->getTypeInstance(true)->getSetAttributes($p);
            $attributes['media_gallery']->getBackend()->updateImage($p, $image["file"], array('postion'=>$image['postion'],'postion_default'=>$image['postion_default'],'label'=>$image['label'],'label_default'=>$image['label_default'],'disabled'=>$image['disabled'],'disabled_default'=>$image['disabled_default']));

There is exact one image in $mediaGallery. The Script imports two entries (one is empty). The other entry is correct but the labels (for each store) are missing.

Any idea?

  • Have you tried dumping the $mediaGallery["images"] array to see if there is an empty one in there? If yes, just do a if($image["file"] !='') after you start your foreach loop.
    – tecjam
    Oct 26, 2015 at 15:55
  • Yes, of course: array(2) { ["images"]=> array(1) { [0]=> array(8) { ["value_id"]=> string(1) "1" ["file"]=> string(12) "/3/_/3_0.jpg" ["label"]=> string(14) "Test" ["position"]=> string(1) "0" ["disabled"]=> string(1) "1" ["label_default"]=> string(14) "Test" ["position_default"]=> string(1) "0" ["disabled_default"]=> string(1) "1" } } ["values"]=> array(0) { } } Oct 26, 2015 at 16:03

1 Answer 1


I think better get images by $product->getMediaGalleryImages();

And then foreach loop:

   $images = $product->getMediaGalleryImages();
   foreach ($images as $image) {
       // Check if the file path exists
       if( $path = $image->getPath() ) {
           $anotherProduct->addImageToMediaGallery($path, array('image','thumbnail','small_image'), false, false);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.