Setting Alt Text on Magento Product Images in Bulk

Setting Alt Text on Magento Product Images in Bulk

Product images without labels hurt accessibility and image search. If a catalogue was imported without them, this function sets the label for every image on a product, defaulting to the product name.

The function

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();   
}

Run it over your product collection in batches, and write labels that describe the image rather than repeating keywords.

Heads up: this guide applies to Magento 1, which stopped receiving official security updates in June 2020. If your store still runs it, plan a move to Magento 2 or Adobe Commerce soon. We can help with the migration.

Want this done for you? Find out more about our Magento development service.

Keep reading

Related articles

All articles

Need a hand?

Stuck on something similar?
We can fix it with you.

Send us the problem. A senior developer reads every message and replies within one working day.