Accessibility PHP Intermediate

Tell Screen Reader Users When a Link Opens a New Tab

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.

Tested on WordPress 7.1 PHP 8.3 No plugin needed Updated
functions.php 16 lines
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 );

Where to add this

Recommended A code snippets plugin Survives theme changes and is easy to switch off.
Child theme At the end of your child theme's functions.php file.
Must-use plugin As a .php file in wp-content/mu-plugins, starting with <?php.

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.

How it works

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.

Things to watch

  • Your theme needs the screen-reader-text class. Most themes have it. If the text shows on screen, add “Add the Screen Reader Text CSS”.
  • Only post content is changed, not menus or widgets.

How to test it

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.

This website uses cookies to enhance your browsing experience and ensure the site functions properly. By continuing to use this site, you acknowledge and accept our use of cookies.

Accept All Accept Required Only