Return to Snippet

Revision: 51375
at December 3, 2011 05:44 by RainyDayMedia


Updated Code
function add_alt_tags($content)
{
	global $post;
	preg_match_all('/<img (.*?)\/>/', $content, $images);
	if(!is_null($images))
	{
		foreach($images[1] as $index => $value)
		{
			if(!preg_match('/alt=/', $value))
			{
				$new_img = str_replace('<img', '<img alt="'.get_the_title().'"', $images[0][$index]);
				$content = str_replace($images[0][$index], $new_img, $content);
			}
		}
	}
	return $content;
}
add_filter('the_content', 'add_alt_tags', 99999);

Revision: 51374
at December 3, 2011 04:55 by RainyDayMedia


Updated Code
function add_alt_tags($content)
{
        global $post;
        preg_match_all('/<img (.*?)\/>/', $content, $images);
        if(!is_null($images))
        {
                foreach($images[1] as $index => $value)
                {
                        if(!preg_match('/alt=/', $value))
                        {
                                $new_img = str_replace('<img', '<img alt="'.get_the_title().'"', $images[0][$index]);
                                $content = str_replace($images[0][$index], $new_img, $content);
                        }
                }
        }
        return $content;
}
add_filter('the_content', 'add_alt_tags', 99999);

Revision: 51373
at September 22, 2011 07:44 by RainyDayMedia


Initial Code
function add_alt_tags($content)
{
        global $post;
        preg_match_all('/<img (.*?)\/>/', $content, $images);
        if(!is_null($images))
        {
                foreach($images[1] as $index => $value)
                {
                        if(!preg_match('/alt=/', $value))
                        {
                                $new_img = str_replace('<img', '<img alt="'.get_the_title().'"', $images[0][$index]);
                                $content = str_replace($images[0][$index], $new_img, $content);
                        }
                }
        }
        return $content;
}
add_filter('the_content', 'add_alt_tags', 99999);


Initial URL
https://forrst.com/posts/Add_Missing_Alt_tags_to_Images_WordPress_Conte-DMO

Initial Description
Simple function - just place it in your theme's functions.php file, save, and you're good to go. If an image in your content is missing the alt tag, it adds that posts title as the alt tag for the image.

It's been recommended to me that I shouldn't be using regex to parse HTML, and I made an attempt to do this with DOMDocument, but it wasn't working out to well. If there are any DOMDocument ninjas around, maybe they could slice this up a little easier.

Update: removed the "(.*?)" from the '/alt=/' regex, just in case an image had an alt already defined, but using single quotes instead.

Initial Title
Add Missing Alt tags to Images - WordPress Content Filter

Initial Tags
wordpress

Initial Language
PHP