Magento 1.12 – Programmatically Update Image Labels

apiee-1.12image

I'm trying to update my product images' labels. I want them to be the same as the name of the product.

What I've tried

$mediaModel = Mage::getModel("catalog/product_attribute_backend_media");
$images = $product->getMediaGalleryImages();
foreach ($images as $image) {
    $mediaModel->updateImage(
        $product->getId(),
        $image->getFile(),
        array("label" => $title)
    );
}

But then I get this error

Fatal error: Call to a member function getAttributeCode() on a non-object in app/code/core/Mage/Catalog/Model/Product/Attribute/Backend/Media.php on line 401

I've also tried

$mediaModel = Mage::getModel("catalog/product_attribute_media_api");
$images = $mediaModel->items($product->getId());
foreach ($images as $image) {    
    $mediaModel->update(
        $product->getId(),
        $image['file'],
        array("label" => $title)
    );
}

Which runs fine, but the values aren't updated in the admin.

How do I go about this?

Best Answer

The following code should work for you.

$product = mage::getModel('catalog/product')->load(16);
$attributes = $product->getTypeInstance(true)->getSetAttributes($product);
$gallery = $attributes['media_gallery'];
$images = $product->getMediaGalleryImages();
foreach ($images as $image) {
    $backend = $gallery->getBackend();
    $backend->updateImage(
        $product,
        $image->getFile(),
        array('label' => 'Blah')
    );
}
$product->getResource()->saveAttribute($product, 'media_gallery');

I was getting an error on simply $product->save(); but saving the one attribute seems to work.

Related Topic