This snippet automatically adds rel="noopener noreferrer" to external links in post content that open in a new tab (target="_blank"). It improves security by preventing the linked page from accessing your website through the window.opener object.
Steps
- Open your active theme’s
functions.phpfile or a custom functionality plugin. - Add the code below.
- Save the file.
- External links with
target="_blank"will automatically include the appropriaterelattributes.
/**
* Add rel="noopener noreferrer" to external links.
*/
function wpfolks_secure_external_links( $content ) {
$content = preg_replace_callback(
'/<a([^>]+)target=["']_blank["']([^>]*)>/i',
function( $matches ) {
if ( strpos( $matches[0], 'rel=' ) === false ) {
return str_replace(
'target="_blank"',
'target="_blank" rel="noopener noreferrer"',
$matches[0]
);
}
return preg_replace(
'/rel=["']([^"']*)["']/',
'rel="$1 noopener noreferrer"',
$matches[0]
);
},
$content
);
return $content;
}
add_filter( 'the_content', 'wpfolks_secure_external_links' );