Skip to content

Instantly share code, notes, and snippets.

@gelanivishal
Created March 10, 2017 01:17
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save gelanivishal/46fa627032a3a649929893d90257b084 to your computer and use it in GitHub Desktop.
Add image to product programmatically
<?php
// Add three image sizes to media gallery
$mediaArray = array(
'thumbnail' => $putPathHere,
'small_image' => $putPathHere,
'image' => $putPathHere,
);
// Remove unset images, add image to gallery if exists
$importDir = Mage::getBaseDir('media') . DS . 'import/';
foreach($mediaArray as $imageType => $fileName) {
$filePath = $importDir.$fileName;
if ( file_exists($filePath) ) {
try {
$product->addImageToMediaGallery($filePath, $imageType, false);
} catch (Exception $e) {
echo $e->getMessage();
}
} else {
echo "Product does not have an image or the path is incorrect. Path was: {$filePath}<br/>";
}
}
<?php
require_once 'app/Mage.php';
Mage::app();
Mage::app()->getStore()->setId(Mage_Core_Model_App::ADMIN_STORE_ID);
$importDir = Mage::getBaseDir('media') . DS . 'bulkimages/101/';
$productsData = array('Purple-Crown-Ring-MFAS.jpg','Purple-Crown-Ring-MFC.jpg','Purple-Crown-Ring-MSAS.jpg','Purple-Crown-Ring-MSF.jpg');
$productSKU = '111';
$ourProduct = Mage::getModel('catalog/product')->loadByAttribute('sku',$productSKU);
foreach($productsData as $fileName){
$filePath = $importDir.$fileName;
if (file_exists($filePath)) {
$ourProduct->addImageToMediaGallery($filePath, array('image', 'small_image', 'thumbnail'), false, false);
$ourProduct->save();
echo "done ";
} else {
echo $productSKU . " not done";
echo "<br>";
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment