Steps
-
Add the PHP code to your child theme’s
functions.phpfile or the Code Snippets plugin. -
Save and activate the snippet.
-
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
Reported by the author on October 23, 2026. WPFolks has not verified this.
Not tested against WordPress 7.1.4. It may still work.
