Alana Storm
Alana Storm

Reputation: 166066

Adding Magento's small_image and thumbnail Programmatically

In Magento, the following code will programmatically add an image a product's image gallery

//set store to admin id so we can save a product
Mage::app()->getStore()->setId(Mage_Core_Model_App::ADMIN_STORE_ID);

//load a product with an id of 2514
$product = Mage::getModel('catalog/product')->load('2514');

//add the image
$product->addImageToMediaGallery('/tmp/test.png','image',false,false);        

This, as expected, will add an image to a product's media gallery, and this image will be selected as the product's "Base Image". However, the "small_image" and "thumbnail" images will not be selected for this image.

If the following code is used

$product->addImageToMediaGallery('/tmp/test.png','image',false,false);        
$product->addImageToMediaGallery('/tmp/test.png','small_image',false,false);        
$product->addImageToMediaGallery('/tmp/test.png','thumbnail',false,false);        

Magento will add three new images to the media gallery. One with Base Image selected, one with Small Image selected, and a third with thumbnail.

Is it possible to signal Magento that when you call

$product->addImageToMediaGallery('/tmp/test.png','image',false,false);        

that it should automatically generate the small image and the thumbnail image?

Upvotes: 7

Views: 6104

Answers (3)

Aitor Solana
Aitor Solana

Reputation: 21

This worked for me

To import and set

$id = 2400;
$product = $object_Manager->create('Magento\Catalog\Model\Product')->load($id);
$imageType = ['image', 'small_image', 'thumbnail'];
$imagePath = '/tmp/test.png';
$product->addImageToMediaGallery($imagePath, $imageType, false, false);
$product->setStoreId(0)->save();

Just to set

$id = 2400;
$product = $object_Manager->create('Magento\Catalog\Model\Product')->load($id);
if (!$product->hasImage()) continue;
if (!$product->hasSmallImage()) $product->setSmallImage($product->getImage());
if (!$product->hasThumbnail()) $product->setThumbnail($product->getImage());
$product->setStoreId(0)->save();

Upvotes: 0

Samuel Ng
Samuel Ng

Reputation: 11

I had the same issue as you. The reason the image gets imported but the Media Attributes (Base, Thumbnail, Small) are not showing, is because it is being set in the Child Websites. Instead you want to set it as a Default Value. In other words the Store ID = 0.

Hope that helps. Sam

Upvotes: 1

Barbanet
Barbanet

Reputation: 493

Try with:

$product->addImageToMediaGallery('/tmp/test.png',array('image', 'small_image', 'thumbnail'),false,false); 

Upvotes: 12

Related Questions