Theme & Front End JavaScript Beginner

Open External Links in a New Tab

Make links to other websites open in a new tab, with the safe rel attributes and a hidden notice for screen reader users.

Tested on WordPress 7.1 No plugin needed Updated
script.js 15 lines
document.addEventListener( 'DOMContentLoaded', () => {
	document.querySelectorAll( 'a[href^="http"]' ).forEach( ( link ) => {
		if ( link.hostname === window.location.hostname || link.target ) {
			return;
		}

		link.target = '_blank';
		link.relList.add( 'noopener', 'noreferrer' );

		const notice = document.createElement( 'span' );
		notice.className = 'screen-reader-text';
		notice.textContent = ' (opens in a new tab)';
		link.appendChild( notice );
	} );
} );

Where to add this

Recommended A code snippets plugin As a JavaScript snippet set to load in the footer.
Child theme Save it as a .js file and load it with wp_enqueue_script() from functions.php.
Page builder Your builder's custom code area, set to load in the footer.

Some sites prefer external links to open in a new tab so visitors don’t lose their place. This script does it for every outgoing link, in a way that’s safe and tells screen reader users what will happen.

How it works

The script checks every link whose address starts with “http”. If it points to another domain and doesn’t already have a target, it gets target="_blank" and rel="noopener noreferrer", which stops the new page controlling yours.

A visually hidden “(opens in a new tab)” is added inside the link, using WordPress’s standard screen-reader-text class, so screen reader users aren’t surprised by a new tab.

Things to watch

  • Accessibility guidelines generally recommend letting people choose whether to open a new tab. Only use this if you have a good reason.
  • Make sure your theme’s CSS includes the .screen-reader-text class. WordPress themes are required to.

How to test it

Click an external link on your site. It should open in a new tab, and inspecting it should show the rel attribute and hidden 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