WordPress发布文章添加外部链接时为不传递权重可添加nofollow标签,通过在模板functions.php添加以下可为外部链接自动添加nofollow标签。
function rel_nofollow( $content ) {
return preg_replace_callback( '/<a[^>]+/', 'rel_nofollow_callback', $content );
}
add_filter( 'the_content', 'rel_nofollow', 99999 );
function rel_nofollow_callback( $matches ) {
$link = $matches[0];
$exclude = '('. home_url() .'|http://([^.]+\.)?(wp.org|wp.com))';
if ( preg_match( '#href=\S('. $exclude .')#i', $link ) )
return $link;
if ( strpos( $link, 'rel=' ) === false ) {
$link = preg_replace( '/(?<=<a\s)/', 'rel="nofollow" ', $link );
} elseif ( preg_match( '#rel=\S(?!nofollow)#i', $link ) ) {
$link = preg_replace( '#(?<=rel=.)#', 'nofollow ', $link );
}
return $link;
}