WordPress Tip: Add nofollow to links in post content

WordPress Tip: Add nofollow to links in post content

Nofollow is an HTML attribute value used to instruct some search engines that a hyperlink should not influence the link target's ranking in the search engine's index. Using nofollow, we can control the flow of PageRank from our website to another. And in WordPress blog, it is easily be done just by couple of following lines.

I've created the plugin to do all these things automatically. Please go to the plugin page to download and use.

To insert nofollow to all links in post content, paste the following code into functions.php file:

add_filter('the_content', 'my_nofollow');

function my_nofollow($content) {
    return stripslashes(wp_rel_nofollow($content));
}

Save this file and you can be happy that your PageRank won't run out to other websites.

Update:

One problem of this method is that it adds nofollow to all links in post content, including internal links. It maybe harmful for your blog. By modifying the function, we can add only nofollow to external links in post content as the following code:

add_filter('the_content', 'my_nofollow');

function my_nofollow($content) {
    //return stripslashes(wp_rel_nofollow($content));

    return preg_replace_callback('/<a[^>]+/', 'my_nofollow_callback', $content);
}

function my_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;
}

Put this code into the functions.php file of your theme and enjoy it.

Thank wpexplorer for the idea.

🔥 HOT: Interested in boosting your WordPress SEO? My Slim SEO plugin is a super lighweight and automated plugin that handles most the hard work for you: meta tags, sitemap, redirection, schema & link building.

👉 Have a look and you will love it: wpslimseo.com

Leave a Reply

Your email address will not be published. Required fields are marked *


Copyright © 2024 Deluxe Blog Tips. All rights reserved.

My products: Meta Box | Slim SEO