目录
前言
WordPress自动为站内链接添target="_blank"
属性,以及为站外链接同时添加target="_blank"
和rel="nofollow noopener"
属性,提升访客浏览体验和网站SEO。

使用方法
WordPress后台 > 外观 > 主题文件编辑器 > 点击模板函数
> 将代码粘贴到模板函数文件中 > 最后更新文件
//对所有链接添加target="_blank",并对站外链接添加rel="nofollow noopener"
add_filter('the_content', 'add_nofollow_to_external_links');
function add_nofollow_to_external_links( $content ) {
$anchorTagRegexp = "/<a\s[^>]*href=(\"?)([^\" >]*?)\\1[^>]*>/siU";
if(preg_match_all($anchorTagRegexp, $content, $matches, PREG_SET_ORDER)) {
if( !empty($matches) ) {
$siteUrl = get_option('siteurl');
$newContent = $content;
foreach($matches as $match) {
$originalTag = $match[0];
$modifiedTag = $originalTag;
$url = $match[2];
if (!preg_match('/target\s*=\s*"\s*_blank\s*"/', $modifiedTag)) {
$modifiedTag = preg_replace('/>$/', ' target="_blank">', $modifiedTag);
}
if (strpos($url, $siteUrl) === false && !preg_match('/rel\s*=\s*"\s*nofollow\s*"/', $modifiedTag)) {
$modifiedTag = preg_replace('/>$/', ' rel="nofollow noopener">', $modifiedTag);
}
$newContent = str_replace($originalTag, $modifiedTag, $newContent);
}
$content = $newContent;
}
}
return $content;
}
//WordPress系统对链接添加的rel="nofollow noopener" 替换为 rel="nofollow noopener"
function no_referrer($content) {
$replace = array("noreferrer " => "nofollow " );
$new_content = strtr($content, $replace);
return $new_content;
}
add_filter('the_content', 'no_referrer', 999);
