小七博客使用DUX主题已经有很长一段时间了,由于文章的类型的需求,需要为站外链接添加nofollow属性,一个一个添加比较还是比较麻烦的。现在分享可以用于DUX主题自动为站外链接添加nofollow、链接新窗口打开、blank属性等,具体的的方法把下面的代码添加到DUX主题中的functions-theme.php中,位置可以放置在最后,其他wordpress没有测试,不知道是否有效,如果是其他主题大多数是添加到functions.php中,具体的代码如下:
// 文章外部链接加上nofollow
add_filter( 'the_content', 'cn_nf_url_parse');
function cn_nf_url_parse( $content ) {
$regexp = "<a\s[^>]*href=(\"??)([^\" >]*?)\\1[^>]*>";
if(preg_match_all("/$regexp/siU", $content, $matches, PREG_SET_ORDER)) {
if( !empty($matches) ) {
$srcUrl = get_option('siteurl');
for ($i=0; $i < count($matches); $i++)
{
$tag = $matches[$i][0];
$tag2 = $matches[$i][0];
$url = $matches[$i][0];
$noFollow = '';
$pattern = '/target\s*=\s*"\s*_blank\s*"/';
preg_match($pattern, $tag2, $match, PREG_OFFSET_CAPTURE);
if( count($match) < 1 )
$noFollow .= ' target="_blank" ';
$pattern = '/rel\s*=\s*"\s*[n|d]ofollow\s*"/';
preg_match($pattern, $tag2, $match, PREG_OFFSET_CAPTURE);
if( count($match) < 1 ) $noFollow .= ' rel="nofollow" '; $pos = strpos($url,$srcUrl); if ($pos === false) { $tag = rtrim ($tag,'>');
$tag .= $noFollow.'>';
$content = str_replace($tag2,$tag,$content);
}
}
}
}
$content = str_replace(']]>', ']]>', $content);
return $content;
}
当然也可以使用插件,WordPress插件功能还是非常强大的,多数是免费使用的,可以在后台插件栏目中进行搜索“Nofollow for external link”或者“External Links – nofollow, noopener & new window”等,均可以实现。
注:代码来源于网络,在添加之前请做好相关文件的备份!

VPS推荐网