前言
WordPress自动为站内链接添target="_blank"
属性,以及为站外链接同时添加target="_blank"
和rel="nofollow noopener"
属性,提升访客浏览体验和网站SEO。
//对所有链接添加target="_blank",并对站外链接添加rel="nofollow noopener" add_filter('the_content', 'add_nofollow_to_external_links'); function add_nofollow_to_external_links( $content ) { $anchorTagRegexp = "/]*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);