Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
WordPress: Add missing alt tags
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);
@ahmed-wagdi

This comment has been minimized.

Copy link

commented Apr 14, 2015

Newer versions of wordpress autofill the alt text using the image's file name, any way to change this code to get around that problem?

@ghost

This comment has been minimized.

Copy link

commented Jun 12, 2015

Using get_the_title() to populate image alt tags is a bad idea. If you have multiple images they will all have alt tags that say "6579540 Ways To Be A Rock Star" even if the image is a toilet plunger stuck to someone's head. It's just not good.

@lelebart

This comment has been minimized.

Copy link

commented Apr 24, 2019

Just in case the img has an empty alt tag, change line 9 with something like:
if(!preg_match('/alt=/', $value) || preg_match('/alt=""/', $value))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.