久久精品人人爽,华人av在线,亚洲性视频网站,欧美专区一二三

WordPress網站文章頁外鏈nofollow標簽和新窗口打開方法

232次閱讀
沒有評論

共計 1488 個字符,預計需要花費 4 分鐘才能閱讀完成。

很多 WordPress 網站文章頁外鏈沒有進行優化,如果手動加 nofollow 標簽的話是很麻煩的一件事,所以去互聯網查找了一些方法,發現很多代碼并不起作用,而且網絡東西魚龍混雜,優質的信息反而不容易找到,下面是解決的代碼并記錄下來。

// 給文章外鏈添加 nofollow
add_filter('the_content','web589_the_content_nofollow',999);
function web589_the_content_nofollow($content){preg_match_all('/href="(.*?)"/',$content,$matches);
if($matches){foreach($matches[1] as $val){if( strpos($val,home_url())===false ) $content=str_replace("href="$val"","href="$val" rel="external nofollow" ",$content);
}
}
return $content;
}
// 文章外鏈 nofollow 結束 

自動新窗口打開并同時添加 nofollow 的代碼:

// 出站鏈接自動添加 nofollow 和在新窗口打開
add_filter('the_content', 'auto_nofollow_for_external_link');
function auto_nofollow_for_external_link($content) {$regexp = "<as[^>]*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 = '/targets*=s*"s*_blanks*"/';
                preg_match($pattern, $tag2, $match, PREG_OFFSET_CAPTURE);
                if(count($match) < 1 )
                    $noFollow .= 'target="_blank" ';

                $pattern = '/rels*=s*"s*[n|d]ofollows*"/';
                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;
}

第一種代碼較少,比較簡潔,如果想同時實現 nofollow 標簽和新窗口代開可以使用第二種方法,當然,如果換了主題,上面的代碼要重新安裝。對了,上面的代碼是要放在主題編輯器 functions.php 中保存即可使用。

正文完
 
丸趣
版權聲明:本站原創文章,由 丸趣 2023-06-03發表,共計1488字。
轉載說明:除特殊說明外本站除技術相關以外文章皆由網絡搜集發布,轉載請注明出處。
評論(沒有評論)
主站蜘蛛池模板: 昆明市| 哈巴河县| 施秉县| 筠连县| 伊春市| 长春市| 合江县| 墨竹工卡县| 通化市| 巴楚县| 山东省| 六枝特区| 琼结县| 长葛市| 临夏市| 温州市| 福贡县| 星座| 新蔡县| 新营市| 任丘市| 连城县| 巩义市| 临泽县| 繁昌县| 长葛市| 顺昌县| 义马市| 乌拉特后旗| 福泉市| 都江堰市| 正宁县| 黄冈市| 茶陵县| 抚松县| 资中县| 兴山县| 盐池县| 黄山市| 宜州市| 象山县|