Skip to main content
Login Join
Snippet · PHP

Automatically Add rel=”noopener noreferrer” to External Links

Shared by Amit Dholiya · July 26, 2026 · @the_content

16 views
Back to Snippets

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

  1. Open your active theme’s functions.php file or a custom functionality plugin.
  2. Add the code below.
  3. Save the file.
  4. External links with target="_blank" will automatically include the appropriate rel attributes.
/**
 * 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' );
Know a different way to do this? Add your approach as a variation so folks can compare them side by side.
Submit a variation

0 comments