日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 综合教程 >内容正文

综合教程

纯代码实现WordPress文章中的外链自动添加nofollow和blank属性

發(fā)布時間:2023/11/21 综合教程 32 生活家
生活随笔 收集整理的這篇文章主要介紹了 纯代码实现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)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。