Create a gist now

Instantly share code, notes, and snippets.

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);

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?

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment