WordPress评论链接重定向并在新窗口中打开的方法

为了防止权重流失所以加上nofollow,但搜索引擎还是会抓取评论区的链接,那么应该试一下链接重定向

WordPress评论链接重定向并在新窗口中打开的方法 - 1

1.【链接重定向】在主题的functions.php最后加上这条代码

//评论链接重定向 
add_filter('get_comment_author_link', 'add_redirect_comment_link', 5); 
add_filter('comment_text', 'add_redirect_comment_link', 99); 
function add_redirect_comment_link($text = ''){ 
$text=str_replace('href="', 'href="'.get_option('home').'/?url=', $text);  //url可以自定义
$text=str_replace("href='", "href='".get_option('home')."/?url=", $text);  //url可以自定义 
return $text; 
} 
add_action('init', 'redirect_comment_link'); 
function redirect_comment_link(){ 
$redirect = $_GET['url']; 
if($redirect){ 
if(strpos($_SERVER['HTTP_REFERER'],get_option('home')) !== false){ 
header("Location: $redirect"); 
exit; 
} 
else { 
header("Location: http://www.slll.info/");  //这里修改成自己的站点
exit; 
} 
} 
}

2.【新窗口打开评论链接】修改wp-include中的formatting.php文件,查找function _make_url_clickable_cb这个语句,然后你会看到类似于下面这样的语句。

function _make_url_clickable_cb($matches) {
	$url = $matches[2];

	if ( ')' == $matches[3] && strpos( $url, '(' ) ) {
		// If the trailing character is a closing parethesis, and the URL has an opening parenthesis in it, add the closing parenthesis to the URL.
		// Then we can let the parenthesis balancer do its thing below.
		$url .= $matches[3];
		$suffix = '';
	} else {
		$suffix = $matches[3];
	}

	// Include parentheses in the URL only if paired
	while ( substr_count( $url, '(' ) < substr_count( $url, ')' ) ) {
		$suffix = strrchr( $url, ')' ) . $suffix;
		$url = substr( $url, 0, strrpos( $url, ')' ) );
	}

	$url = esc_url($url);
	if ( empty($url) )
		return $matches[0];

	return $matches[1] . "<a href=\"$url\" rel=\"nofollow\">$url</a>" . $suffix;
}

在最后一句话中添加 target=\”_blank\”就可以了

<a href=\"$url\" target=\"_blank\" rel=\"nofollow\">$url</a>

4 thoughts on “WordPress评论链接重定向并在新窗口中打开的方法”

Leave a Reply to Charl Anders Cancel reply

Your email address will not be published. Required fields are marked *