Home / functions.php / Nofollow external links only, the_content and the_excerpt
  • How to Nofollow external links only, the_content and the_excerpt

    nofollow-external-links-only-the_content-and-the_excerpt

    This great little snippet that will add rel=”nofollow” to external links within both the_content and the_excerpt. Add this snippet to the functions.php of your wordpress theme to enable nofollow external links.

    ( click code to copy )

    wordpress snippet : PHP

    <>
    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;
    }
    

    ( WordPress codex functions, hooks, in this snippet. )

    the_content, the_excerpt, bloginfo, add_filter, _n, _e, _ex, get_bloginfo,