Automatic alt tags on images in WordPress

When you insert an image into a post, the HTML is “hardcoded” into the post content. You can edit the image’s alt text in the Media Library, but this will only include the alt text for future uses of the image. It won’t automatically update all of the past uses of that image in your older posts.

The code below fixes this. When a page loads, it finds all of the images that are missing alt text and looks to see if you’ve specified an alt text for it in the Media Library. If so, it updates the image before loading the page.

Install the plugin

Download this zip file, then go to Plugins > Add New > Upload to install and activate it.

Download Now

You can now go to your Media Library and update the alt text for every image. You won’t have to edit every post and update each instance of the image.

Note: this will only work for posts that are using the Gutenberg block editor. Even if you’re using the block editor now, it’s likely that most of your older content is still using the classic editor.

You can use Bulk Block Converter to convert all the posts using the Classic editor to the Block editor, but be careful. I’d run the tool first on a staging environment and go through your posts to make sure there were no issues with the conversion.

add_filter( 'render_block', function( $content, $block ) { if( 'core/image' !== $block['blockName'] ) return $content; $alt = get_post_meta( $block['attrs']['id'], '_wp_attachment_image_alt', true ); if( empty( $alt ) ) return $content; // Empty alt if( false !== strpos( $content, 'alt=""' ) ) { $content = str_replace( 'alt=""', 'alt="' . $alt . '"', $content ); // No alt } elseif( false === strpos( $content, 'alt="' ) ) { $content = str_replace( 'src="', 'alt="' . $alt . '" src="', $content ); } return $content; }, 10, 2 );
Bill Erickson

Bill Erickson is a freelance WordPress developer and a contributing developer to the Genesis framework. For the past 14 years he has worked with attorneys, publishers, corporations, and non-profits, building custom websites tailored to their needs and goals.

Ready to upgrade your website?

I build custom WordPress websites that look great and are easy to manage.

Let's Talk