站长视角
用户至上

WordPress 教程:DUX主题文章链接添加nofollow标签与新窗口打开

wordpress教程多少都是通用的,如何为文章外链添加target="_blank"rel="nofollow"标签呢,那么下面老杨以国外主机测评使用的DUX主题测试;

具体方法:

  • 找到主题下的functions.php
  • 将以下代码增加到最后面:
// 自动给页面的站外链接添加nofollow属性和新窗口打开
add_filter( 'the_content', 'cn_nf_url_parse');
function cn_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;
}

添加完即可看到效果。

说明:部分主题functions.php进行了加密,可以以添加到相应的主题中的说明文件下,比如DUX可以添加到functions-theme.php最后即可!

赞(0)
版权声明:本文采用知识共享 署名4.0国际许可协议 [BY-NC-SA] 进行授权, 转载请注明出处。
文章名称:《WordPress 教程:DUX主题文章链接添加nofollow标签与新窗口打开》
文章链接:https://www.sshce.com/19320.html
【声明】:国外主机测评仅分享信息,不参与任何交易,也非中介,所有内容仅代表个人观点,均不作直接、间接、法定、约定的保证,读者购买风险自担。一旦您访问国外主机测评,即表示您已经知晓并接受了此声明通告。
【关于安全】:任何 IDC商家都有倒闭和跑路的可能,备份永远是最佳选择,服务器也是机器,不勤备份是对自己极不负责的表现,请保持良好的备份习惯。
香港110M(含10M CN2)大带宽独服限量促销,香港E3-8G-1T硬盘-3IP,月付仅799!

登录

找回密码

注册