cancel
Showing results for 
Search instead for 
Did you mean: 

Adding Alt Tags to all images

Adding Alt Tags to all images

Is there a plugin or a script which can be used to populate alt images for all images across a site? 

4 REPLIES 4

Re: Adding Alt Tags to all images

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.

Re: Adding Alt Tags to all images

Re: Adding Alt Tags to all images

is this working

 

Re: Adding Alt Tags to all images

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.

BdV en Linea