Magento – Set Sort order for Product Images and Save Programatically

magento-1.7magento-1.8product-images

I have an option to add products and its images in frontend. All the product details are saved correctly.But I want to set sort order for each image.

Below is the code to store product images,it's working good. But with this I want to set sort order also.

foreach($_FILES['images']['name'] as $key=>$files)
{
    $absolute_path = Mage::getBaseDir('media').DS.'catalog'.DS.'product'.DS.$f.DS.$s.DS.$files;

                $mediaArray = array(
                        'thumbnail'   => $absolute_path,
                        'small_image' => $absolute_path,
                        'image'       => $absolute_path,
                    );
                    foreach($mediaArray as $imageType => $files)
                    {
                        $filePath = $files;
                        if(file_exists($filePath)) 
                        {
                            try
                            {
                                $product->addImageToMediaGallery($filePath, $imageType, false, false);
                            } 
                            catch (Exception $e)
                            {
                                echo $e->getMessage();
                            }
                        } 
                        else 
                        {
                            echo "Product does not have an image or the path is incorrect. Path was: {$filePath}<br/>";
                        }
                  }
}

Best Answer

With addImageToMediaGallery it is not possible to add position to the image,

you will need to use media->getBackend()->updateImage() after uploading the image,

but updateImage() needs second parameter image path of the uploaded image,

you can get it with media->getBackend()->addImage() it returns the filename, have a look at code for some hints

$product = Mage::getModel('catalog/product')->load(123);

$attributes = $product->getTypeInstance(true)->getSetAttributes($product);

$media_gallery = $attributes['media_gallery'];

$backend = $media_gallery->getBackend();

$backend->afterLoad($product);

$count = count($product->getMediaGalleryImages()) + 1;

if($product->getImage() && $product->getImage() != 'no_selection'){
    $media_attributes = null;
}else{
    $media_attributes = array('image','small_image','thumbnail');
}
$filename = $media_gallery->getBackend()->addImage($product, $import, $mediaAttribute,false, false);
$attributes['media_gallery']->getBackend()->updateImage($product, $filename, array('position' => $count));

$product->save();
Related Topic