The WPFolks app is out on iPhone and Android. Free, no ads. Download on the App Store Get it on Google Play
Skip to main content
Login Join
Snippet · PHP

Automatically Add Nofollow to External Links in WordPress Content

Shared by Amit Dholiya · October 26, 2026

7 views
Back to Snippets

Steps

  1. Add the PHP code to your child theme’s functions.php file or the Code Snippets plugin.

  2. Save and activate the snippet.

  3. Open a published post containing external links and inspect the link HTML.

Hook Used

– the_content — Filters the post content before it is displayed.

Type: WordPress SEO Customization

Output: HTTP and HTTPS links to external domains receive rel="nofollow" if they do not already have it.

Important: This simple implementation compares hostnames exactly, so links using www versus non-www may be treated as external. It also does not automatically add sponsored or ugc; use those attributes where appropriate.

function custom_add_nofollow_to_external_links( $content ) {
    if ( is_admin() || ! is_singular() ) {
        return $content;
    }

    $site_host = wp_parse_url( home_url(), PHP_URL_HOST );

    return preg_replace_callback(
        '/<ab[^>]*bhrefs*=s*(["'])(.*?)1[^>]*>/i',
        function ( $matches ) use ( $site_host ) {
            $url  = $matches[2];
            $host = wp_parse_url( $url, PHP_URL_HOST );

            if (
                ! $host ||
                strtolower( $host ) === strtolower( $site_host ) ||
                ! in_array( wp_parse_url( $url, PHP_URL_SCHEME ), array( 'http', 'https' ), true )
            ) {
                return $matches[0];
            }

            $tag = $matches[0];

            if ( preg_match( '/brels*=s*(["'])(.*?)1/i', $tag, $rel_match ) ) {
                $rels = preg_split( '/s+/', strtolower( $rel_match[2] ) );

                if ( ! in_array( 'nofollow', $rels, true ) ) {
                    $new_rel = trim( $rel_match[2] . ' nofollow' );
                    $tag = preg_replace(
                        '/brels*=s*(["'])(.*?)1/i',
                        'rel="' . esc_attr( $new_rel ) . '"',
                        $tag,
                        1
                    );
                }
            } else {
                $tag = rtrim( substr( $tag, 0, -1 ) ) . ' rel="nofollow">';
            }

            return $tag;
        },
        $content
    );
}
add_filter( 'the_content', 'custom_add_nofollow_to_external_links', 20 );

Tested on

WordPress 6.8

Reported by the author on October 23, 2026. WPFolks has not verified this.

Not tested against WordPress 7.1.4. It may still work.

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

Proudly supported by