Add hidden "(opens in a new tab)" text to links in posts that open in a new tab, so screen reader users aren't surprised.
add_filter( 'the_content', function ( string $content ): string {
if ( ! str_contains( $content, '_blank' ) ) {
return $content;
}
return preg_replace_callback(
'#(<a\s[^>]*target=(["\'])_blank\2[^>]*>)(.*?)(</a>)#is',
function ( array $m ): string {
if ( str_contains( $m[3], 'opens in a new tab' ) ) {
return $m[0];
}
return $m[1] . $m[3] . '<span class="screen-reader-text"> (opens in a new tab)</span>' . $m[4];
},
$content
);
}, 30 );
Always add PHP to a staging site first, or have FTP or file manager access ready, so you can undo it if something goes wrong.
When a link opens a new tab, sighted users notice the new tab. Screen reader users often don’t, and then the Back button stops working for them. WCAG recommends warning people in advance. This snippet adds the warning automatically.
The snippet looks for links with target="_blank" in post content and adds a <span class="screen-reader-text"> just before the closing </a>. Screen readers read it as part of the link; sighted visitors don’t see it.
Links that already contain the phrase are skipped, and it runs after “Open External Links in a New Tab” so it catches those links too.
screen-reader-text class. Most themes have it. If the text shows on screen, add “Add the Screen Reader Text CSS”.Add a link set to open in a new tab and view the post with a screen reader, or inspect the link. It should contain the hidden “(opens in a new tab)” text.