I am using custom script to import products in magento. product thumbnail or small image set using the code but the base image not set. I am using the below code :

            $mediaArray = array(
                'image'       => $data['image'],
                'thumbnail'   => $data['image'],
                'small_image' => $data['image']

            // Remove unset images, add image to gallery if exists
            $importDir = Mage::getBaseDir('media') . DS . 'import/product/';
            //echo $importDir;exit;
            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/>";

What is the missing in the code. Can anyone suggest the solution ?

2 Answers 2


You need to add your code above the product save code :


Hope it will work.


Please use below code for assign base image for a product if not assign.

$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 (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);

echo($c . " product(s) updated.");

Hope so it helps you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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