Magento – How to update media_gallery attribute

imageimage-previewproduct

Is there anyway that I can update the media_gallery attribute of a product? I do have an array of data for media_gallery like this…

{
    ["sku"] => string(4) "8676"
    ["media_gallery"] => object(stdClass)#67 (2) {
      ["images"] => array(1) {
        [0] => object(stdClass)#35 (8) {
          ["value_id"] => string(4) "2270"
          ["file"] => string(38) "/d/e/den-lille-bibel-bog-og-plakat.jpg"
          ["label"] => string(0) ""
          ["position"] => string(1) "1"
          ["disabled"] => string(1) "0"
          ["label_default"] => string(0) ""
          ["position_default"] => string(1) "1"
          ["disabled_default"] => string(1) "0"
        }
      }
      ["values"] => array(0) {
      }
    }
    ["image"] => string(12) "no_selection"
    ["small_image"] => string(12) "no_selection"
    ["thumbnail"] => string(12) "no_selection"
  }

is there any $product->setMediaGallery(); method ?

Best Answer

Try below code, i hope it will help you

 $prodID = '2121';//product ID  
 $mediaApi = Mage::getModel("catalog/product_attribute_media_api"); 
 $_product = Mage::getModel('catalog/product')->load($prodID);
    $items = $mediaApi->items($_product->getId());
    foreach($items as $item) {
        $data =  array(
            'file' => array(
                'name' => 'file_name',
                'content' => base64_encode(file_get_contents('product.jpg')),
                'mime'    => 'image/jpeg'
            ),
            'label'    => 'Cool Image Through Soap',
            'position' => 2,
            'types'    => array('small_image'),
            'exclude'  => 0
        );
        $mediaApi->update($_product->getId(), $item['file'],$data);
    }