Skip to content

Instantly share code, notes, and snippets.

@meminuygur
Created August 14, 2017 20:21
Show Gist options
  • Save meminuygur/8f3689a495894346ba7b1b86ee4b47b9 to your computer and use it in GitHub Desktop.
Save meminuygur/8f3689a495894346ba7b1b86ee4b47b9 to your computer and use it in GitHub Desktop.
Product Add Image Programmatically
<?php
require_once('../app/Mage.php'); //Path to Magento
umask(0);
Mage::app();
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
$product_ids = Mage::getModel('catalog/product')->getCollection()->getAllIds();
$c=0;
foreach( $product_ids as $id ) {
$c++;
//for remove existing Images
$product =Mage::getModel('catalog/product')->load($id);
$mediaApi = Mage::getModel("catalog/product_attribute_media_api");
$mediaApiItems = $mediaApi->items($product->getId());
foreach($mediaApiItems as $item) {
$datatemp=$mediaApi->remove($product->getId(), $item['file']);
}
$product->save(); //before adding need to save product
$imagepath = '/srv/users/serverpilot/apps/dev/public/urunfoto/'.$product->getSku().'.png';
_echo( $c.'--------'.$product->getSku().'----------' );
if( file_exists($imagepath)) {
_echo('varr : '.$imagepath);
$product->setMediaGallery (array('images'=>array (), 'values'=>array ()));
$product->addImageToMediaGallery($imagepath,array('image','small_image','thumbnail'),true,false);
try{
$product->save();
_echo('save ok');
}catch (Exception $e){
_echo('hata:'. $e->getMessage());
}
} else{
_echo( 'yokk : '.$imagepath);
}
}
function _echo($message){
Mage::log($message, null, 'image_import.log', true);
echo $message."\r\n";
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment