1

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>";
    }   
}

?>
3

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>";
    }   
}
?>
  • glad you got this sorted, you can mark this answer as accepted if you think it will help others @mcoder – Prashant Barot Jul 21 '16 at 7:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.