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="http://www.w3.org/2001/XMLSchema-instance" 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" />
</type>
</config> |
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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" />
</type>
</config>
Now the Plugin’s code. The function we’re targeting is getGalleryImages
,
File: app/code/Vendor/Module/Block/Product/View/Gallery/Plugin.php
<?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
if(!$image->getLabel()){
$image->setLabel($product->getName());
}
}
}
return $images;
}
} |
<?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
if(!$image->getLabel()){
$image->setLabel($product->getName());
}
}
}
return $images;
}
}
And that’s it.