How to use wp_rel_nofollow to add nofollow to external links only?

wp_rel_nofollow() add nofollow attribute to all links so we can not use it or may be I am not sure how.

You can use this function to add rel="nofollow" to all external links. This function will check all links in content against your blog/website URL (as internal domain) and add nofollow attribute if both does not match.

function add_nofollow_external_links( $content ) {
    return preg_replace_callback( '/<a>]+/', 'auto_nofollow_callback', $content );
}
function auto_nofollow_callback( $matches ) {
    $link = $matches[0];
    $site_link = get_bloginfo('url');
    if (strpos($link, 'rel') === false) {
        $link = preg_replace("%(href=S(?!$site_link))%i", 'rel="nofollow" $1', $link);
    } elseif (preg_match("%href=S(?!$site_link)%i", $link)) {
        $link = preg_replace('/rel=S(?!nofollow)S*/i', 'rel="nofollow"', $link);
    }
    return $link;
}
add_filter( 'the_content', 'add_nofollow_external_links' );

not tested.

Leave a Comment