WordPress 实现文章链接新窗口打开,站外链接自动加nofollow
以下是Wordpress做网站过程中常用的几个功能,分享给学习建网站的新手们。
功能一:文章内容全部链接新窗口打开
function Bing_autoblank($text) {
$return = str_replace('<a','<a target="_blank"',$text);
return $return;
}
if( Bing_get_panel('post_url_blank') ) add_filter('the_content','Bing_autoblank');
功能二:文章内容外链自动添加 nofollow 并在新窗口打开
function Bing_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;
}
if( Bing_get_panel('post_url_blank_nofollow') ) add_filter('the_content','Bing_nf_url_parse');
功能三:评论作者链接新窗口打开
function Bing_comment_author_link() {
$url = get_comment_author_url( $comment_ID );
$author = get_comment_author( $comment_ID );
if ( empty( $url ) || 'http://' == $url ) return $author;
return '<a href="'. $url .'" rel="external nofollow" target="_blank" class="url">'.$author.'</a>';
}
add_filter('get_comment_author_link', 'Bing_comment_author_link');