WordPress 设置所有链接在新窗口打开(target=”_blank”)

2023-05-3010:34:29网站管理维护Comments1,769 views字数 670阅读模式

让自己 WordPress 博文中的所有链接都在新窗口打开,这样原页面就不会被覆盖,可以方便用户再切换回来。今天老王就介绍一个自动给文章中所有的链接添加 target=”_blank” 属性的方法,举一反三,在这个方法的基础上,你也可以添加 nofollow 属性,或者只有外链才用新窗口打开等等。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/wg/43415.html

方法很简单,在你 WordPress 主题的 functions.php 文件中添加如下代码:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/wg/43415.html

add_filter('the_content','the_content_blank',999);
function the_content_blank($content) {
    preg_match_all('/<a(.*?)href="(.*?)"(.*?)>/',$content,$matches);
    if($matches){
        foreach($matches[2] as $val){
            if(strpos($val, "#")===false && !preg_match('/\.(jpg|jepg|png|ico|bmp|gif|tiff)/i',$val)) {
                $content = str_replace( "href=\"".$val."\"", " target=\"_blank\" "."href=\"".$val."\"", $content );
            }
        }
    }
    return $content;
}

如果你想只有非本站的链接才在新窗口打开,那么就再加一个判断条件:strpos($val,home_url())===false,基于这个方法,基本你想对文章中的链接进行什么操作都可以实现了。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/wg/43415.html

  • 本站内容整理自互联网,仅提供信息存储空间服务,以方便学习之用。如对文章、图片、字体等版权有疑问,请在下方留言,管理员看到后,将第一时间进行处理。
  • 转载请务必保留本文链接:https://www.cainiaoxueyuan.com/wg/43415.html

Comment

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定