• Hi,

    I’m using the below code to add target-blank and noopener to all external links on my website. But when I try to add nofollow to a specific link (using WordPress editor), this doesn’t work as the link gets overridden by the code. Is there a way to modify the code such that it doesn’t interfere with adding the nofollow attribute?

    function add_target_blank($content) {
     $content = preg_replace_callback('/]*href=["|\']([^"|\']*)["|\'][^>]*>([^<]*)<\/a>/i', function($m) {
        if (strpos($m[1], "https://example.com") === false)
            return '<a href="'.$m[1].'" target="_blank" rel="noopener">'.$m[2].'</a>';
        else
            return '<a href="'.$m[1].'">'.$m[2].'</a>';
       }, $content);
    return $content;
    }
    add_filter('the_content', 'add_target_blank');
Viewing 1 replies (of 1 total)
  • Hello!

    Please add the following functions code in active theme functions.php file

    add_filter(‘the_content’, ‘my_nofollow’);
    add_filter(‘the_excerpt’, ‘my_nofollow’);

    function my_nofollow($content) {
    return preg_replace_callback(‘/<a[^>]+/’, ‘my_nofollow_callback’, $content);
    }
    function my_nofollow_callback($matches) {
    $link = $matches[0];
    $site_link = get_bloginfo(‘url’);
    if (strpos($link, ‘rel’) === false) {
    $link = preg_replace(“%(href=\S(?!$site_link))%i”, ‘rel=”nofollow” $1’, $link);
    } elseif (preg_match(“%href=\S(?!$site_link)%i”, $link)) {
    $link = preg_replace(‘/rel=\S(?!nofollow)\S*/i’, ‘rel=”nofollow”‘, $link);
    }
    return $link;
    }

    Hope it helps!
    Thanks

Viewing 1 replies (of 1 total)
  • The topic ‘About adding the nofollow tag’ is closed to new replies.