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標簽與新窗口打開》
文章鏈接:http://www.lrracing.com/19320.html
【聲明】:國外主機測評僅分享信息,不參與任何交易,也非中介,所有內容僅代表個人觀點,均不作直接、間接、法定、約定的保證,讀者購買風險自擔。一旦您訪問國外主機測評,即表示您已經知曉并接受了此聲明通告。
【關于安全】:任何 IDC商家都有倒閉和跑路的可能,備份永遠是最佳選擇,服務器也是機器,不勤備份是對自己極不負責的表現,請保持良好的備份習慣。