bux23 of Micons
4/12/2017 - 10:43 AM

Automate images with missing alt tags using image filename - Wordpress

Automate images with missing alt tags using image filename - Wordpress

<?php
//////////////////////////////////////////////////////////////
///////// AUTOMATE ALT TAGS FOR IMAGES 
//////////////////////////////////////////////////////////////
function image_alt_tag($content) {
	global $post;
	preg_match_all('/<img (.*?)\/>/', $content, $images);
	if(!is_null($images)) {
		foreach($images[1] as $index => $value) {
			if(!preg_match('/alt=/', $value) && preg_match('/< *img[^>]*src *= *["\']?([^"\']*)/i', $value)) {
                preg_match('/< *img[^>]*src *= *["\']?([^"\']*)/i', $value, $src);
                $path_parts = pathinfo($src[0]);
                $filename = $path_parts['filename'];
				$new_img = str_replace('<img', '<img alt="'.$filename.'"', $images[0][$index]);
				$content = str_replace($images[0][$index], $new_img, $content);
			}
		}
	}
	return $content;
}
add_filter('the_content', 'image_alt_tag', 999);
?>