Setting default image programmatically
-
12-12-2019 - |
Question
I have the following function for auto uploading images and setting the default one:
function importImages($sku, $image_url, $is_default){
$product = Mage::getModel('catalog/product')->loadByAttribute('sku', $sku);
$image_type = substr(strrchr($image_url,"."),1); //find the image extension
$filename = md5($image_url . $sku).'.'.$image_type; //give a new name, you can modify as per your requirement
$filepath = Mage::getBaseDir('media') . DS . 'import'. DS . $filename; //path for temp storage folder: ./media/import/
file_put_contents($filepath, file_get_contents(trim($image_url))); //store the image from external url to the temp storage folder
if($is_default==true){
//$product->setMediaGallery(array('images'=>array (), 'values'=>array ()));
$mediaAttribute = array ( 'image',
'small_image',
'thumbnail'
);
}else{
$mediaAttribute = null;
}
$product->addImageToMediaGallery($filepath, $mediaAttribute, true, false);
$product->save();
}
The problem is that the default images isn't setted up as expected.
La solution
I have experienced that this would not store the images as default images in a multi side store. In order to accomplish this, I had to add the following code after $product->save();
:
$value=$product->getData('small_image');
if ($value) {
Mage::getSingleton('catalog/product_action')
->updateAttributes(array($product->getId()),
array(
'image'=>$value,
'small_image'=>$value,
'thumbnail'=>$value,
),
0); // 0 specifies the Default
}
Autres conseils
See the below link for details:
https://stackoverflow.com/questions/8456954/magento-programmatically-add-product-image
Add below code
foreach($mediaAttribute as $imageType)
{
$product->addImageToMediaGallery($filePath, $imageType, false);
}
to after
$mediaAttribute = array ('image','small_image', 'thumbnail'
);
Modified code is
$is_default=true;
$product = Mage::getModel('catalog/product')->loadByAttribute('sku', $sku);
$image_type = substr(strrchr($image_url,"."),1); //find the image extension
$filename = md5($image_url . $sku).'.'.$image_type; //give a new name, you can modify as per your requirement
$filepath = Mage::getBaseDir('media') . DS . 'import'. DS . $filename; //path for temp storage folder: ./media/import/
file_put_contents($filepath, file_get_contents(trim($image_url))); //store the image from external url to the temp storage folder
if($is_default==true){
//$product->setMediaGallery(array('images'=>array (), 'values'=>array ()));
$mediaAttribute = array ( 'image',
'small_image',
'thumbnail'
);
foreach($mediaAttribute as $imageType)
{
$product->addImageToMediaGallery($filePath, $imageType, false);
}
}else{
$mediaAttribute = null;
$product->addImageToMediaGallery($filepath, $mediaAttribute, true, false);
}
$product->save();
Licencié sous: CC-BY-SA avec attribution
Non affilié à magento.stackexchange