WordPress过滤APPEND nofollow到rel

问题描述 投票:0回答:1

我正在尝试追加nofollow添加外部链接。如果链接没有rel属性,则会添加rel="nofollow"。如果链接已经有rel="nofollow",则不会发生任何事情,如果链接有rel=something else,则还应添加nofollow值。

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

代码成功地将rel=follow添加到外部链接但是如果例如链接有rel="noopener" it will replace it willrel = follow. Why is it no appending like so?rel =“noopener nofollow”

regex wordpress filter
1个回答
0
投票

因为你忽略了<a>标签的所有属性,除了href。如果您想考虑现有的rel值,您也应该阅读它。也许用一些html解析器函数更容易,因为regexp对你的情况来说有点太低了。

© www.soinside.com 2019 - 2024. All rights reserved.