1

I've been working on a batch interface for clients to be able to create products programatically on Magento, which is working well. I've got images uploading into the media/import folder and then being imported into Magento with the following code;

<?php $product = Mage::getModel('catalog/product')->load($entity);?>
  <?php if(file_exists($path."/".$filename)):?>
    <?php $product->addImageToMediaGallery($path."/".$filename, array('image', 'small_image', 'thumbnail'), false, false);?>
    <?php $gallery = $product->getData('media_gallery');?>
    <?php $lastImage = array_pop($gallery['images']);?>
    <?php $lastImage['label'] = $name;?>
    <?php array_push($gallery['images'], $lastImage);?>
    <?php $product->setData('media_gallery', $gallery);?>
    <?php $product->setData('has_images','1');?>
    <?php $product->getResource()->saveAttribute($product,'has_images');?>
    <?php $product->save();?>
  <?php endif;?>

This was based on a mixture of solutions from a few users, and seems to correctly import the files into the storage system with automatic appending of numerics on duplicate filenames.

The only problem I get is that by then calling the images back using the following code, images added via the script are ignored and I'm really not sure why!

<?php foreach($product->getMediaGalleryImages() as $image):?>
  <img src="<?php echo Mage::helper('catalog/image')->init($product, 'image', $image->getFile())->resize(100, 100); ?>"/>
<?php endforeach;?>
  • figured it out, in order for the images to be registered, the product must first have a blank image array saved, pushing an item into the array saves it correctly for the product to work, but doesn't update the internal image index. – Duncan Wardlaw Sep 8 '16 at 9:19
2

When creating the product you MUST add a blank array for images, otherwise the image index for the product will not be updated when adding via script.

 ->setMediaGallery (array('images'=>array (), 'values'=>array ()))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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