You may want to change all external links on a page to ‘nofollow’ attribute. You might want to do this for search engine optimization purpose. ‘Nofollow’ provides a way for webmasters to tell search engines “Don’t follow links on this page” or “Don’t follow this specific link”.

WordPress automatically adds a rel=”nofollow” attribute to external links in comments, but it doesn’t happen automatically within post content. If you want to automatically add ‘nofollow’ attribute to external links in your post content without using any plug-in, add the following code in theme’s functions.php file.

function auto_nofollow($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 Hook */
add_filter('the_content', 'auto_nofollow');

Adding ‘nofollow’ attribute is not always a good idea for SEO. Do it only when you can make sure this is good for your website.

You may also be interested in our other articles on add .pdf media type to media manager, remove feeds form wordpress, allow more tags in comments and disable auto generated paragraph tags.

Leave a Reply