Magento : Update Image Labels Programmatically
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();
}
