php - 将 rel ="nofollow"添加到 WordPress 帖子中的所有链接

标签 php wordpress

我想向我的 WordPress 帖子中的所有链接添加 rel="nofollow",并且我希望能够获得不会获得 nofollow 的链接列表。

我已经尝试了很多,但我无法正确完成它,因为我真的不太了解正则表达式。

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

最佳答案

假设您向不希望被关注的链接添加了一个类...

$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 添加到除上面定义的类之外的所有链接。

关于php - 将 rel ="nofollow"添加到 WordPress 帖子中的所有链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5948268/

相关文章:

php - 一次有两个变量的 switch 语句

php - cakephp 分页显示错误 : An Internal Error Has Occurred

javascript - 第三个下拉列表值依赖于 jquery 的前两个下拉列表

javascript - jQuery 无法在 Wordpress 中工作 - 默认情况下工作

php - 测试变量是否可序列化

php - 将textarea中的文本插入MySQL数据库而不丢失格式

php - 隐藏 Woocommerce 订阅价格中的 “free trial” 文本,但保留注册费

php - wordpress 将参数传递给自定义模板

php - 如何解决ORA-12154 : TNS error when using PHP OCI8 oci_connect in Azure

php - 获取具有特定 meta_key 且其 meta_value 在 WooCommerce 中相等的所有产品