0

I am trying append nofollow to add external links. If a link does not have a rel attribute, rel="nofollow" will be added. If a link already has rel="nofollow" nothing will happen, and if a link has rel=something else the nofollow value should also be added.

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

The code successfully adds rel=follow to external links but if for a example a link has rel="noopener" it will replace it willrel=follow. Why is it no appending like so?rel="noopener nofollow"`

  • You're explicitly returning a link with just rel="nofollow". You'll need to add a condition inside your if(strpos($m[1], $mydomain) === false) { condition to check to see whether the rel attribute is there, and if so, append nofollow to it. – WebElaine Apr 18 at 18:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.