Adding rel=”nofollow” to all links in WordPress posts

I want to add a rel=”nofollow” to all the links in my wordpress posts and I want to be able to have a list of links that won’t get the nofollow.

I have been trying a lot, but I can’t get it done right, because I really can’t understand regex very well.

Read More

So I have the string $text and I want to replace a href=”url”> with a href=”url” rel=”nofollow”> unless the href matches some specific domains.

Related posts

Leave a Reply

1 comment

  1. Say you added a class to links you don’t want to be followed…

    $skipClass = 'preserve-rel';
    
    $dom = new DOMDocument;
    
    $dom->loadHTML($str);
    
    $anchors = $dom->getElementsByTagName('a');
    
    foreach($anchors as $anchor) { 
        $rel = array(); 
    
        if ($anchor->hasAttribute('class') AND preg_match('/b' . preg_quote($skipClass, '/') . 'b/', $anchor->getAttribute('class')) {
           continue;
        }
    
        if ($anchor->hasAttribute('rel') AND ($relAtt = $anchor->getAttribute('rel')) !== '') {
           $rel = preg_split('/s+/', trim($relAtt));
        }
    
        if (in_array('nofollow', $rel)) {
          continue;
        }
    
        $rel[] = 'nofollow';
        $anchor->setAttribute('rel', implode(' ', $rel));
    }
    
    var_dump($dom->saveHTML());
    

    This will add nofollow to all links except ones with a class defined above.