Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I have lots of images that has to be uploaded via media library. I want to know, is it possible to add file name to alt attribute field automatically when I am uploading them? At the moment I have to open each image and add the alt attribute manually.

share|improve this question
add comment

1 Answer

A viable solution I found was adding the post title to images missing the ALT attribute.

Add the following to your functions.php file:

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

Alternatively, if you want to replace the attribute with the file name, you could look into using the get_attached_file function for the $new_img variable.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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