Add default alt attribute to all product images in Magento 2

Here’s another good use of the handy Plugin feature introduced in Magento 2.

To make product name as the default value of all product image’s ‘alt’ attribute, all we need to do is to create a simple Plugin.

First, declare the Plugin in your custom module’s di.xml

File: app/code/Vendor/Module/etc/frontend/di.xml

<?xml version="1.0"?>
<config xmlns:xsi="" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\Catalog\Block\Product\View\Gallery">
	<plugin name="vendor_module_block_product_view_gallery_plugin" type="Vendor\Module\Block\Product\View\Gallery\Plugin" sortOrder="10" />

Now the Plugin’s code. The function we’re targeting is getGalleryImages,

File: app/code/Vendor/Module/Block/Product/View/Gallery/Plugin.php

namespace Vendor\Module\Block\Product\View\Gallery;
class Plugin
    public function afterGetGalleryImages($block, $images)
        if ($images instanceof \Magento\Framework\Data\Collection) {
            $product = $block->getProduct();
            foreach ($images as $image) {
                //check if label is set
        return $images;

And that’s it.

3 thoughts on “Add default alt attribute to all product images in Magento 2”

  1. Thank for the tip. It is working nicely in my development mode (of m2.0.14). Unfortunately I am not sure why it is not working when I deployed the changes to Production while using production mode.
    Is there any other things I should do beside applying the changes?

    Thank you very much in advance.

  2. This is working perfectly fine!! Thanks for this nice blog.

    How can we achieve same thing for product listing pages.

Comments are closed.