how to set base image in coding while adding image programmatically
-
12-12-2019 - |
Question
I added the code to update the product images programmatically.
Please refer the below code
$firstProduct = Mage::getModel ('catalog/product')
->load($firstProductId);
$firstProduct->setMediaGallery (array('images'=>array (), 'values'=>array ()))
->addImageToMediaGallery(
$filePath,
array('image','thumbnail'),
false,
false
);
$firstProduct->save();
/*debug*/
$mediaGallery = $firstProduct->getMediaGallery();
print_r($mediaGallery);
My doubt here is, how to set added image as base image.
Thank you for your valuable inputs
Solution
To save product base image use this,
if(//baseimage only one time)
{
$mediaAttribute = array (
'image',
'thumbnail',
'small_image'
);
}
else
{
$mediaAttribute = null;
}
$product->addImageToMediaGallery($filepath_to_image, $mediaAttribute, true, false);
Edited
//3rd param is move, if it is true then move source file
//4th param is exclude,if true mark image as disabled in product page view
if you create a new product then, setting it with second attribute array as 'image','thumbnail','small_image'
automatically set as base image,
or if you edit your product,
then just save new image as base with first condition i given, it sets default base image.
OTHER TIPS
I've got this working for Magento 1.9
<?php
require 'app/Mage.php';
Mage::app();
$products = Mage::getModel('catalog/product')->getCollection()->addAttributeToSelect('*')->setPageSize(5000);
foreach ($products as $product) {
$gallery_images = Mage::getModel('catalog/product')->load($product->getId())->getMediaGalleryImages();
$path = $gallery_images->toArray()["items"][0]["file"];
if (!$product->hasImage()) continue;
if (!$product->hasSmallImage()) $product->setSmallImage($path);
if (!$product->hasThumbnail()) $product->setThumbnail($path);
$product->save();
}
?>
Please use below code for assign base image for a product if not assign.
<?php
set_time_limit(0);
include_once "app/Mage.php";
Mage::init();
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
$app = Mage::app();
$products = Mage::getResourceModel('catalog/product_collection');
$c = 0;
foreach($products as $p){
$pid = $p->getId();
$product = Mage::getModel('catalog/product')->load($pid);
//get all images
$mediaGallery = $product->getMediaGallery();
//if($product->getImage() != "no_selection" ){ OR
if($product->getImage()){
continue;
}else{
if (isset($mediaGallery['images'])){
//loop through the images
foreach ($mediaGallery['images'] as $image){
//set the first image as the base image
Mage::getSingleton('catalog/product_action')->updateAttributes(array($product->getId()), array('image'=>$image['file'],'small_image'=>$image['file'],'thumbnail'=>$image['file']), 0);
$c++;
break;
}
}
}
}
echo($c . " product(s) updated.");
?>
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange