Question

I tried to change the default position for each image in product.

            $products = mage::getModel('catalog/product')->load(1311);
            $attributes = $products->getTypeInstance(true)->getSetAttributes($products);
            $gallery = $attributes['media_gallery'];
            $images = $products->getMediaGalleryImages();
            foreach ($images as $image) {
             $attributes['media_gallery']->getBackend()->updateImage($products, $image->getFile(), $data=array('label'=>'good','position'=>10,'position_default'=>11));
            }
            $products->getResource()->saveAttribute($products, 'media_gallery');
            $products->save();

From the above code, the image position is changed but image position default is not changed.

        [value_id] => 25865
        [file] => /2/0/20_Tulips.jpg
        [label] => good
        [position] => 10
        [disabled] => 0
        [label_default] => 
        [position_default]=>
Was it helpful?

Solution

Try the below code to change the default position for one image.

    $product = Mage::getModel('catalog/product')->load(120);
    $sku = $product->getSku();
    $media = Mage::getModel('catalog/product_attribute_media_api');
    $absolute_path = Mage::getBaseDir('media').DS.'catalog'.DS.'product'.DS.$f.DS.$s.DS.$filename;
    $position = 0;
        if (file_exists($absolute_path)) { 
            $pathInfo = pathinfo($absolute_path);

        switch($pathInfo['extension']){
            case 'png':
                $mimeType = 'image/png';
                break;
            case 'jpg':
                $mimeType = 'image/jpeg';
                break;
            case 'gif':
                $mimeType = 'image/gif';
                break;
        }

 $types = ($position == 0) ? array('image', 'small_image', 'thumbnail') : array();
 $newImage = array(
            'file' => array(
                'content' => base64_encode($absolute_path),
                'mime' => $mimeType,
                'name' => basename($absolute_path),
                ),
            'label' => 'whatever', // change this. 
            'position' => $position,
            'types' => $types,
            'exclude' => 0,
        );

        $media->create($sku, $newImage);
        // OR (if you would rather use the product entity ID):
        // $media->create($productId, $newImage, null, 'id');

    } else {
        echo "image not found";
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top