Magento – Programatically add images to product using sku

gallerymagento-1.9

i have uploaded 1000's of product with images wrong so i deleted images from table , now issue is that i want to correct all images via mapping with sku.

How i add images to product programatically using product sku?

For product i have array of images for example for product with sku 123

I have image array 1.png,2.png,3.png . now i want 1.png should be thumbnail,small_image,image and rest all to be added to gallery .

How can it be done?

atached is my code that works fine but all images comes as gallery image i want to set first one as base small and thumb image

<?php
require_once 'app/Mage.php';
Mage::app();
Mage::app()->getStore()->setId(1);


$importDir = 'bulkimages/101/';

$productsData = array('Purple-Crown-Ring-MFAS.jpg','Purple-Crown-Ring-MFC.jpg','Purple-Crown-Ring-MSAS.jpg','Purple-Crown-Ring-MSF.jpg');


foreach($productsData as $fileName){
    $productSKU = '111';
    $ourProduct = Mage::getModel('catalog/product')->loadByAttribute('sku',$productSKU);
    $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>";
    }   
}

?>

Best Answer

You must have to put your images in media folder and est full path. Please check the below code i changed.

<?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>";
    }   
}
?>
Related Topic