1

I'm adding images to products programmatically. Every product can have from 1 to n images. So I reorder the images array in the way I need and then, to the first image of the array (that has to be the first to be displayed in the product page and in the product list view) I set the media_attribute as needed (image, small_image, thumbnail).

Everything seems to work fine, and images are correctly ordered in the product details, but small image and thumbnail are not set.

This is the piece of code I'm using to add images (the usual used everywhere)

ksort($prod_images);
foreach($prod_images as $key=>$img){
    $imgPath = $dirName . $img;

    try{
        if($key == 1){
            $prod->addImageToMediaGallery($imgPath, array('image', 'small_image','thumbnail'), false, false);
        }else{
            $prod->addImageToMediaGallery($imgPath, null, false, false);
        }
        $prod->save();
    }catch(\Exception $e){
    }       
}

I eventually managed to set the correct image as small/thumb/base if I reverse the array and add it as last image, but in this way the image order is wrong and I need to preserve it or eventually change it, but I could not find a way for that.

Any clue?

EDIT

I found a patch, but it does not actually satisfy me... after saving the product for the first time, I recall the existing images and set the first as base/thumb/small, and it seems to work, but it actually waste a lot of time...

so I'm still looking for a real solution.

  • Try to unset existing image entry $product->getMediaGalleryEntries(); before add new images – Prince Patel Mar 9 '18 at 5:50
  • I'm already doing it before setting the new images. – sissy Mar 9 '18 at 8:05

Your Answer

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

Browse other questions tagged or ask your own question.