Name Links That Contain Only an Image Without Alt Text
Gives links in your content whose only content is an image with empty alt text an accessible name, using the title of the page they point to, so screen readers no longer announce just the URL.
Opens WPIDE on
Code
add_filter( 'the_content', function ( $content ) {
if ( false === stripos( $content, '<img' ) ) {
return $content;
}
return preg_replace_callback( '#<a\b([^>]*)>\s*(<img\b[^>]*>)\s*</a>#i', function ( $m ) {
if ( preg_match( '#\baria-label=#i', $m[1] ) || ( preg_match( '#\balt=(["\'])(.*?)\1#i', $m[2], $alt ) && '' !== trim( $alt[2] ) ) ) {
return $m[0];
}
if ( ! preg_match( '#\bhref=(["\'])(.*?)\1#i', $m[1], $href ) ) {
return $m[0];
}
$url = html_entity_decode( $href[2] );
$key = 'wpide_linkname_' . md5( $url );
$post_id = wp_cache_get( $key, 'wpide' );
if ( false === $post_id ) {
$post_id = (int) url_to_postid( $url );
wp_cache_set( $key, $post_id, 'wpide', HOUR_IN_SECONDS );
}
if ( ! $post_id ) {
return $m[0];
}
return '<a' . $m[1] . ' aria-label="' . esc_attr( wp_strip_all_tags( get_the_title( $post_id ) ) ) . '">' . $m[2] . '</a>';
}, $content );
}, 20 );
Notes
Only links to pages and posts on your own site can be named automatically; looked-up titles are cached.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.