歲月留聲

如何让 WordPress 评论者链接在新标签中打开?

WordPress 博客或网站,查看文章/页面评论,点击评论者名字一般会直接跳到评论者留下的链接,如何让 WordPress 评论者链接在新标签中打开?

如何让 WordPress 评论者链接在新标签中打开? - 第1张图片

「如何让 WordPress 评论者链接在新标签中打开?:https://0xo.net/480」

实现 WordPress 评论者链接在新标签中打开主要有两种方法,一是修改/wp-includes/comment-template.php 文件,不推荐这种方法,每次升级 WordPress 都要重新修改。

二是在主题 functions.php 中添加自定义函数实现 WordPress 评论者的网站链接新窗口打开。代码如下:

//评论内容外部链接 评论者链接 uxtt.com 新标签打开
function comment_redirect_link($link) {
//外链转内链
preg_match_all('/<a(.*?)href="(.*?)"(.*?)>/',$link,$matches);
if( $matches ){
foreach( $matches[2] as $key => $val ){
if( strpos($val,'://')!==false && strpos($val,home_url())===false && !preg_match('/\.(jpg|jepg|png|ico|bmp|gif|tiff)/i',$val) ){
$link=str_replace("href=\"$val\"", "href=\"$val\" target=\"_blank\" rel=\"nofollow noopener\"",$link);
}
}
}
return $link;
}
add_filter( 'comment_text', 'comment_redirect_link' );//评论
add_filter( 'get_comment_author_link', 'comment_redirect_link' );//评论者链接 新标签打开

以上代码会将评论内容和评论者链接添加 blank 和 nofollow,实现在新标签页中打开。

「如何让 WordPress 评论者链接在新标签中打开?:https://0xo.net/480」

如果使用 WordPress 默认的 2023 twentytwentythree 主题,直接安装 External Links in New Window / New Tab 插件吧,启用即可,方便快捷。

「如何让 WordPress 评论者链接在新标签中打开?:https://0xo.net/480」
退出移动版