Automatic alt tags on images in WordPress

tdrayson

I had a client project where the client went through the entire media library and added alt tags to every image. This was great, however Gutenberg only adds alt tags at the point you insert the image.

After doing a brief search on Google, I came across a snippet on Bill Erickson’s site that automatically adds alt tags to every core/image block before it’s rendered on the frontend.

I need to extend the snippet to add support for GenerateBlocks/image block.

Snippet

Add the code below to functions.php or code snippet plugin. You can extend this snippet to support other image blocks by adding the block-path to the $target_blocks array and also a new item in the switch statement. Every block stores the image ID differently.

PHP

        add_filter('render_block', 'tct_add_alt_tags', 10, 2);
function tct_add_alt_tags($content, $block){
	$block_name = $block['blockName'];
    
    $target_blocks = [
        'core/image', 
        'generateblocks/image'
    ];
	
	if( !in_array($block_name, $target_blocks) ) return $content;
    
    switch($block_name){
        case 'generateblocks/image':
            $id = $block['attrs']['mediaId'];
            break;
        default:
            $id = $block['attrs']['id'];
            break;
    }

	$alt = get_post_meta( $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;	
}
      
Copy

👋🏻 Weekly Tutorial Digest

I send out a weekly newsletter with links to new tutorials written in the last week, you can subscribe below.

Newsletter

🔒I won't send you spam, I promise