当我使用代码时:
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;
}
只有在_content和_except中,链接才会获得nofollow属性。我可以如何编辑代码,整个wordpress网站都使用这个功能(页脚,侧边栏…(
谢谢
一个好的脚本,它允许自动添加nofollow并保留其他属性
function nofollow(string $html, string $baseUrl = null) {
return preg_replace_callback(
'#<a([^>]*)>(.+)</a>#isU', function ($mach) use ($baseUrl) {
list ($a, $attr, $text) = $mach;
if (preg_match('#href=["']([^"']*)["']#', $attr, $url)) {
$url = $url[1];
if (is_null($baseUrl) || !str_starts_with($url, $baseUrl)) {
if (preg_match('#rel=["']([^"']*)["']#', $attr, $rel)) {
$relAttr = $rel[0];
$rel = $rel[1];
}
$rel = 'rel="' . ($rel ? (strpos($rel, 'nofollow') ? $rel : $rel . ' nofollow') : 'nofollow') . '"';
$attr = isset($relAttr) ? str_replace($relAttr, $rel, $attr) : $attr . ' ' . $rel;
$a = '<a ' . $attr . '>' . $text . '</a>';
}
}
return $a;
},
$html
);
}
我们的想法是在加载和过滤所有内容后,将您的操作添加到完整的html缓冲区中,而不仅仅是在"内容"区域中。请仔细阅读!!!!此操作是verry RAW和低级。。。你真的可以用这些缓冲动作把一切都搞砸。但也很高兴知道;-(它是这样工作的:
add_action( 'wp_loaded', 'buffer_start' ); function buffer_start() { ob_start( "textdomain_nofollow" ); }
add_action( 'shutdown', 'buffer_end' ); function buffer_end() { ob_end_flush(); }
然后执行替换操作并设置回调:请将$buffer变量想象成HTML中的完整站点,因为它将被加载。
function textdomain_nofollow( $buffer ) {
return preg_replace_callback( '/<a[^>]+/', 'textdomain_nofollow_callback', $buffer );
}
以下是我如何进行href检查(阅读我的评论(:
function textdomain_nofollow_callback( $matches ) {
$link = $matches[0];
// if you need some specific external domains to exclude, just use :
//$exclude = '('. home_url() .'|(http|https)://([^.]+.)?(domain-to-exclude.org|other-domain-to-exclude.com)|/)';
// By default, just exclude your own domain, and your relative urls that starts by a '/' (if you use relatives urls)
$exclude = '('. home_url() .'|/)';
if ( preg_match( '#href=S('. $exclude .')#i', $link ) )
return $link;
if ( strpos( $link, 'rel=' ) === false ) {
$link = preg_replace( '/(?<=<as)/', 'rel="nofollow" ', $link );
} elseif ( preg_match( '#rel=S(?!nofollow)#i', $link ) ) {
$link = preg_replace( '#(?<=rel=.)#', 'nofollow ', $link );
}
return $link;
}
根据我的经验,它运行良好。。。Q