Is there a plugin or a script which can be used to populate alt images for all images across a site?
Hi @jake_jackson ,
You can create following files in your custom module in order to achieve this.
Vendor Name: Vendor
Module Name: Module
File: Vendor/Module/etc/frontend/events.xml
<?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd"> <event name="controller_front_send_response_before"> <observer name="add_alt_tags" instance="Vendor\Module\Observer\AddAltTags"/> </event> </config>
File: Vendor/Module/etc/Observer/AddAltTags.php
<?php namespace Vendor\Module\Observer; class AddAltTags implements \Magento\Framework\Event\ObserverInterface { public function execute(\Magento\Framework\Event\Observer $observer) { $response = $observer->getResponse(); $body = $response->getBody(); $body = $this->replaceAlt($body, 'Alt Text to add'); $response->setBody($body); return $this; } public function replaceAlt($html_content, $alt_text='') { $count = preg_match_all('/<img[^>]+>/i', $html_content, $images); if($count>0) { $o = $html_content; $t = 'alt="'.$alt_text.'" '; foreach($images[0] as $img) { $is_alt = preg_match_all('/ alt="([^"]*)"/i', $img, $alt); if($is_alt==0) { $new_img = str_replace('<img ', '<img '.$t , $img); $o = str_replace($img, $new_img, $o); } elseif($is_alt==1) { $text = trim($alt[1][0]); if(empty($text)) { $new_img = str_replace(trim($alt[0][0]), $t, $img); $o = str_replace($img, $new_img, $o); } } } } return $o; } }
This will add alt text "Alt Text to add" wherever alt text is not present in your html. You can play with the code to explore more options. This will only affect to frontend.
Hope this helps.
Hello @jake_jackson
Found this extension if that helps
https://marketplace.magento.com/fme-seo-images-alt-tag.html
https://www.cynoinfotech.com/product/seo-images-alt-tags-magento-2-extension/
is this working
Dont know why its hapenning. pleased to see your issue as I think I have the same problem I am also confused and in need of light on this same issue. Need help.