添加rel =“nofollow"到 Wordpress 帖子中的所有链接 [英] Adding rel="nofollow" to all links in Wordpress posts

查看:22
本文介绍了添加rel =“nofollow"到 Wordpress 帖子中的所有链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的 wordpress 帖子中的所有链接中添加一个 rel="nofollow",并且我希望能够拥有一个不会获得 nofollow 的链接列表.

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.

所以我有字符串 $text 并且我想用 href="url" rel="nofollow"> 替换 href="url"> 除非 href 匹配某些特定域.

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());

这会将 nofollow 添加到除具有上面定义的类的链接之外的所有链接.

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

这篇关于添加rel =“nofollow"到 Wordpress 帖子中的所有链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆