纯代码实现WordPress文章中的外链自动添加nofollow和blank属性
生活随笔
收集整理的這篇文章主要介紹了
纯代码实现WordPress文章中的外链自动添加nofollow和blank属性
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
wp默認文章中的鏈接是不加target="_blank"屬性的,點擊外鏈會跳走,體驗不太好,修改方法如下:
將下面的代碼添加到當前主題的 functions.php 文件即可
functions.php 文件路徑:/wp-content/themes/主題/functions.php
自動給文章/頁面的站外鏈接添加nofollow屬性(rel=”nofollow”),并且在新窗口打開這些鏈接(即添加 target=”_blank”屬性)。如果已經(jīng)手動給鏈接添加了 rel=”dofollow”,就不會添加 rel=”nofollow”;如果手動添加了 target=”_blank”,就不會重復添加
// 站外鏈接自動添加nofollow屬性
add_filter( 'the_content', 'url_autoblank');
function url_autoblank( $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;
}
總結(jié)
以上是生活随笔為你收集整理的纯代码实现WordPress文章中的外链自动添加nofollow和blank属性的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 总投资5亿元!张家口又一大数据中心项目启
- 下一篇: 10nm Tiger Lake处理器首发