Magento 1.9 – How to Add Image to Product Programmatically

magento-1.9

I have a script to import a list of product from xls. It works fine except for the image; I use the following bits of code:

...

if(file_exists(Mage::getBaseDir('media') . DS . 'import' . DS . $gallery_img)){
    $product->addImageToMediaGallery(Mage::getBaseDir('media') . DS . 'import' . DS . $gallery_img, null, false, false);
}

...

The image is actually added to the product but it's not selected, so it does not show in the frontend:

enter image description here

How can I "select" it programmatically?

Thanks

Best Answer

If you check Magento's addImageToMediaGallery function located at app\code\core\Mage\Catalog\Model\Product.php file,

public function addImageToMediaGallery($file, $mediaAttribute=null, $move=false, $exclude=true)

You will see that second attribute is code of attribute with type 'media_image'. This attribute will define which image will be set as which media image.
By default there are three.

  1. image
  2. small_image
  3. thumbnail

So you need to pass value to your second argument as below

$product->addImageToMediaGallery(Mage::getBaseDir('media') . DS . 'import' . DS . $gallery_img, array('image', 'small_image', 'thumbnail'), false, false);

to set them as main image, small image and thumbnail image.

Related Topic