为WordPress 文章中的链接自动添加 nofollow标签

nofollow 标签是神马东东在这里不多说,请自行谷歌。默认的话,WordPress是不会为你的文章的链接添加rel="nofollow"的。如果你需要这么做的话,不必一个个手动添加,直接在主题的funtions .php文件那里加入以下代码就可以自动实现了。

add_filter('the_content', 'auto_nofollow');

function auto_nofollow($content) {
    //return stripslashes(wp_rel_nofollow($content));

    return preg_replace_callback('/<a>]+/', 'auto_nofollow_callback', $content);
}

function auto_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;
}
展开评论