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

2022-03-22 781阅读

温馨提示:这篇文章已超过768天没有更新,请注意相关的内容是否还可用!

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

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

方法一

/**
 * WordPress外链自动新窗口打开并添加nofollow属性 - 方法一
 * 
 */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属性 - 方法二
 * 
 */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;}


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