Add nofollow to External Links in Content
Adds rel="nofollow" to links in posts and pages that point to other websites, while keeping any rel values already set. Links to your own domain are untouched.
Opens WPIDE on
Code
// Domains whose links stay followed (your own domain is always followed).
$wpide_follow_domains = array( 'wordpress.org' );
add_filter( 'the_content', function ( $content ) use ( $wpide_follow_domains ) {
if ( false === stripos( $content, '<a ' ) ) {
return $content;
}
$own = wp_parse_url( home_url(), PHP_URL_HOST );
$result = preg_replace_callback( '/<a\s[^>]*>/i', function ( $m ) use ( $own, $wpide_follow_domains ) {
$tag = $m[0];
if ( ! preg_match( '/href=["\'](https?:)?\/\/([^\/"\':?#]+)/i', $tag, $href ) ) {
return $tag;
}
$host = strtolower( $href[2] );
foreach ( array_merge( array( $own ), $wpide_follow_domains ) as $domain ) {
$domain = strtolower( (string) $domain );
if ( $host === $domain || substr( $host, -strlen( '.' . $domain ) ) === '.' . $domain ) {
return $tag;
}
}
if ( preg_match( '/\srel=(["\'])([^"\']*)\1/i', $tag, $rel ) ) {
if ( preg_match( '/\bnofollow\b/i', $rel[2] ) ) {
return $tag;
}
return str_replace( $rel[0], ' rel="' . esc_attr( trim( $rel[2] . ' nofollow' ) ) . '"', $tag );
}
return substr( $tag, 0, -1 ) . ' rel="nofollow">';
}, $content );
return null === $result ? $content : $result;
}, 20 );
Notes
Add domains you trust to $wpide_follow_domains to keep their links followed.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.