Programmatically Update Image Labels
Question
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?
Solution
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.
OTHER TIPS
The above code didn't work for me. Here is the changed code that end up working:
function _SetProductImagesAlt($product, $altText='') {
if (is_numeric($product))
{
$product = mage::getModel('catalog/product')->load($product);
}
else //reload the product
{
$product = mage::getModel('catalog/product')->load($product->getId());
}
//set alt to the name of the Product if not set otherwise
if (empty($altText))
{
$altText = $product->getName();
}
//sanitize string
$altText = str_replace("\r", "", $altText);
$altText = str_replace("\n", "", $altText);
$altText = htmlspecialchars($altText, ENT_QUOTES, 'UTF-8');
$attributes = $product->getTypeInstance(true)->getSetAttributes($product);
$images = $product->getMediaGalleryImages();
$mediaGalleryBackendModel = $attributes['media_gallery']->getBackend();
foreach ($images as $image) {
$mediaGalleryBackendModel->updateImage($product, $image->getFile(), array('label' => $altText));
}
$product->save();
}
Note: the reloading of the product object in the line 8 turned out to be important if you used the same object to add a new product beforehand.