Skip to main content
Login Join
Snippet · PHP

Auto Add Nofollow to External Links

Shared by Darshit Rajyaguru · May 20, 2026 · @the_content

1 copy
46 views
1 upvote
Back to Snippets

Automatically adds rel=”nofollow” to external links.

function dr_external_links_nofollow( $content ) {
    return preg_replace_callback(
        '/<a[^>]+href=["'](http[^"']+)["'][^>]*>/i',
        function( $matches ) {
            $host = parse_url( home_url(), PHP_URL_HOST );

            if ( strpos( $matches[1], $host ) === false ) {
                return str_replace( '<a ', '<a rel="nofollow" ', $matches[0] );
            }

            return $matches[0];
        },
        $content
    );
}
add_filter( 'the_content', 'dr_external_links_nofollow' );
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