简体   繁体   中英

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM