WordPress: Fill Missing/Empty ALT Tags with TITLE for SEO

There is a mobile optimized version of this page, view AMP Version.

One of the biggest SEO requirements is for images to have an ALT attribute for indexing and usability purposes, unfortunately when making posts most often ALT attributes are not set leading to lots and lots of posts with images missing their ALT attributes.

I wrote a small function that will capture the page before output and check all the images on the page, any images without an ALT or with a blank ALT will be modified so that the ALT tag is set to the page title, this not only removes the problem of missing ALT tags but will also hopefully boost your page title's authority and images on the page will have the same ALT description as the main page title.

It's easy to use just paste the code below into your functions.php file:

<?php
function callback($buffer) {
	/* modify buffer here, and then return the updated code*/
	
	$title='';
	$res = preg_match('/<title>(.*?)<\/title>/', $buffer, $title_matches);

	if ($res) {
		/*Clean up title: remove EOL's and excessive whitespace.*/
		
		$title = preg_replace('/\s+/', ' ', $title_matches[1]);
		$title = trim($title);
	}

	preg_match_all('/<img (.*?)\/>/', $buffer, $images);
	if(!is_null($images)) {
		foreach($images[1] as $index => $value) {
			preg_match('/alt="(.*?)"/', $value, $img);
			preg_match('/alt=\'(.*?)\'/', $value, $img2);
			if(!is_null($images)) {
				if((!isset($img[1]) || $img[1] == '') || (!isset($img2[1]) || $img2[1] == '')) {
					$new_img = str_replace('<img', '<img alt="'.$title.'"', $images[0][$index]);
					$buffer = str_replace($images[0][$index], $new_img, $buffer);
				}
			}
		}
	}

return $buffer;
}

function buffer_start() { ob_start(); }

function buffer_end() { echo callback(ob_get_clean()); }

add_action('wp', 'buffer_start', 0);
add_action('wp_footer', 'buffer_end');
?>

Note: This may potentially slow the page a little on low spec servers, so having a good cache plugin is recommended.

Author: Dean Williams

I'm a Web Developer, Graphics Designer and Gamer, this is my personal site which provides PHP programming advice, hints and tips

Post Tags:
, , ,