tiger-sms ChatGPT 账号/ChatGPT 代注册 OpenAI API 代充值

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

dajiaka OpenAI API key

有时候我们想让自己 WordPress 博文中的所有链接都在新窗口打开,这样原页面就不会被覆盖,可以方便用户再切换回来。今天老王就介绍一个自动给文章中所有的链接添加 target=”_blank” 属性的方法,举一反三,在这个方法的基础上,你也可以添加 nofollow 属性,或者只有外链才用新窗口打开等等。

方法很简单,在你 WordPress 主题的 functions.php 文件中添加如下代码:

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,基于这个方法,基本你想对文章中的链接进行什么操作都可以实现了。

拓展阅读:《WordPress 非插件版添加 nofollow 标签与外链跳转页面

赞(1)
关注我们
未经允许不得转载:老王博客 » WordPress 设置所有链接在新窗口打开(target=”_blank”)