0

I would like to generate to generate some kind of automatic alt attributes for the images, if they don't have alt set up.

Found this code, but it doesn't work for some reason:

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;
}
add_filter('the_content', 'add_alt_tags', 99999);

1 Answer 1

0

Maybe not the best solution, but did it like this:

function add_alt_tags($content)
{
    global $post;
    $content = str_replace('alt=""', 'alt="'.$post->post_title .'"',
    $content);
    return $content;
}
add_filter('the_content', 'add_alt_tags', 100);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.