Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add rel="nofollow" and target="_blank" for external links permanently

Tags:

wordpress

I would like to add rel="nofollow" and target="_blank" for all external links in my Wordpress posts and pages permanently. I am aware, that there are plugins, which do the same, but as soon as they get disabled, all changes will be reversed and the articles are the same as from the beginning.

I do not know how to differ between internal or external links nor how to check if there is already a rel="nofollow" or target="_blank" attribute.

I guess the best way of doing this would be using PHP instead of MySQL. I already searched the web for guides, tutorials or plugins, without success.

May someone help me? I appreciate your support.

like image 547
Otaku Kyon Avatar asked Mar 16 '23 00:03

Otaku Kyon


2 Answers

I have got a solution for applying nofollow to all existing and new external links. Copy the code into your functions.php of your activated theme

function add_nofollow_content($content) {
$content = preg_replace_callback('/]*href=["|\']([^"|\']*)["|\'][^>]*>([^<]*)<\/a>/i', function($m) {
    if (strpos($m[1], "YOUR_DOMAIN_ADDRESS") === false)
        return '<a href="'.$m[1].'" rel="nofollow" target="_blank">'.$m[2].'</a>';
    else
        return '<a href="'.$m[1].'" target="_blank">'.$m[2].'</a>';
    }, $content);
return $content;
}
add_filter('the_content', 'add_nofollow_content');

You can also call the function home_url() instead of "YOUR_DOMAIN_ADDRESS" in the space provided to avoid hard coding of the domain name.

The code is tested and it works. Hope this one helps.

like image 140
Rony Samuel Avatar answered May 02 '23 21:05

Rony Samuel


You can use following snippet: http://wpsnipp.com/index.php/functions-php/nofollow-external-links-only-the_content-and-the_excerpt/

This great little snippet that will add rel=”nofollow” to external links within both the_content and the_excerpt. Add this snippet to the functions.php of your wordpress theme to enable nofollow external links.

add_filter('the_content', 'my_nofollow');
add_filter('the_excerpt', 'my_nofollow');
function my_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;
}
like image 23
Samuel Avatar answered May 02 '23 21:05

Samuel