FriendlyWP
11/1/2013 - 9:46 PM

Automatically add 'alt' tags to images if none exist. (Credit: https://gist.github.com/svil4ok/1991931)

Automatically add 'alt' tags to images if none exist. (Credit: https://gist.github.com/svil4ok/1991931)

// AUTOMATICALLY ADD ALT TAGS TO IMAGES
add_filter('the_content', 'add_alt_tags', 99999);
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="'.$post->post_title.'"', $images[0][$index]);
                                $content = str_replace($images[0][$index], $new_img, $content);
                        }
                }
        }
        return $content;
}