WordPress.org

Forums

Fixing image ALT attributes that are either empty or using the file name (1 post)

  1. adamwalter
    Member
    Posted 12 months ago #

    I am currently using this code to find images with empty ALT attributes and replace them with the post title:

    function vtl_add_alt_tags($content) {
            global $post;
            preg_match_all('/<img (.*?)\/>/', $content, $images);
            if( !is_null($images) ) {
                foreach($images[1] as $index => $value) {
                    print_r($images);
                    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', 'vtl_add_alt_tags', 99999);

    It works well, but WordPress has the default behavior of adding an image's filename as the ALT attribute unless you tell it otherwise. So, since the ALT isn't empty, my code leaves it alone. In a perfect world my clients would learn to always customize their ALTs, but that will never happen all the time. What I would like to add to my code is a check to see if the ALT attribute is equal to the image's filename. If it is, it would replace the value with the post title.

    I don't think my current approach will make this easy because it grabs the IMG element's guts as a string, disconnecting it from the actual image in WordPress, making it impossible to query its filename.

    Any ideas out there?

Reply

You must log in to post.

About this Topic