缙哥哥的博客
与你分享我的点点滴滴生活

WordPress外链自动新窗口打开并添加nofollow属性

280G全国流量的电信星海卡仅需29元/月,长期可续该套餐,随时可注销

今天群里有人问缙哥哥如何在WordPress站点上,给外链自动添加nofollow属性。因为每次设置太麻烦,所以缙哥哥的博客很早之前就弄了,今天有人提起,就分享给大家!

两种方法均为修改 functions.php 文件。

方法一

/**
 * WordPress外链自动新窗口打开并添加nofollow属性 - 方法一
 * https://www.dujin.org/12336.html
 */
function cleris_url($atts, $url = null){
	extract( shortcode_atts(array('title' => null, 'href' => null), $atts) );
	return '<span class="u-download"><a target="_blank" title="'.$title.'" href="'.$href.'" rel="external nofollow" target="_blank">'.$url.'</a></span>';
}

——《WordPress 外链新窗口打开并添加 nofollow 属性

方法二

/**
 * WordPress外链自动新窗口打开并添加nofollow属性 - 方法二
 * https://www.dujin.org/12336.html
 */
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;
}

好了,教程到此为止,有什么问题可以在下方留言告诉缙哥哥!

赞(10) 打赏
转载请注明来源及链接:缙哥哥 » WordPress外链自动新窗口打开并添加nofollow属性

评论 抢沙发

评论前必须登录!

 

觉得文章有用就打赏一下文章作者

非常感谢你的打赏,我们将继续给力更多优质内容,让我们一起创建更加美好的网络世界!

支付宝扫一扫

微信扫一扫

登录

找回密码

注册