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;
}

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

7f8039ba62c36dc72400825223e1a35a

相关文章