WordPress標簽Tag自動內(nèi)鏈(非插件)
先看效果
可實現(xiàn)文章內(nèi)容頁TAG標簽自動添加鏈接。
實現(xiàn)步驟:
將下列代碼添加到當前主題Functions.php文件中。如果有沖突出現(xiàn)問題,我們需要檢查是不是不兼容。檢查不出來的話,我們只能使用插件實現(xiàn)。反正是能不用插件就不用。
//自動TAG轉(zhuǎn)內(nèi)鏈
$match_num_from = 2; // 一個TAG標簽出現(xiàn)幾次才加鏈接
$match_num_to = 1; // 同一個標簽加幾次鏈接
add_filter('the_content','tag_link',1);
function tag_sort($a, $b){
if ( $a->name == $b->name ) return 0;
return ( strlen($a->name) > strlen($b->name) ) ? -1 : 1;
}
function tag_link($content){
global $match_num_from,$match_num_to;
$posttags = get_the_tags();
if ($posttags) {
usort($posttags, "tag_sort");
foreach($posttags as $tag) {
$link = get_tag_link($tag->term_id);
$keyword = $tag->name;
$cleankeyword = stripslashes($keyword);
$url = "<a href=\"$link\" title=\"".str_replace('%s',addcslashes($cleankeyword, '$'),__('View all posts in %s'))."\"";
$url .= ' target="_blank"';
$url .= ">".addcslashes($cleankeyword, '$')."</a>";
$limit = rand($match_num_from,$match_num_to);
$content = preg_replace( '|(<a[^>]+>)(.*)('.$ex_word.')(.*)(</a[^>]*>)|U'.$case, '$1$2%&&&&&%$4$5', $content);
$content = preg_replace( '|(<img)(.*?)('.$ex_word.')(.*?)(>)|U'.$case, '$1$2%&&&&&%$4$5', $content);
$cleankeyword = preg_quote($cleankeyword,'\'');
$regEx = '\'(?!((<.*?)|(<a.*?)))('. $cleankeyword . ')(?!(([^<>]*?)>)|([^>]*?</a>))\'s' . $case;
$content = preg_replace($regEx,$url,$content,$limit);
$content = str_replace( '%&&&&&%', stripslashes($ex_word), $content);
}
}
return $content;
}
聲明:
1.本站主要是為了記錄工作、學(xué)習(xí)中遇到的問題,可能由于本人技術(shù)有限,內(nèi)容難免有紕漏,一切內(nèi)容僅供參考。
2.本站部分內(nèi)容來源互聯(lián)網(wǎng),如果有圖片或者內(nèi)容侵犯您的權(quán)益請聯(lián)系我們刪除!
3.本站所有原創(chuàng)作品,包括文字、資料、圖片、網(wǎng)頁格式,轉(zhuǎn)載時請標注作者與來源。
1.本站主要是為了記錄工作、學(xué)習(xí)中遇到的問題,可能由于本人技術(shù)有限,內(nèi)容難免有紕漏,一切內(nèi)容僅供參考。
2.本站部分內(nèi)容來源互聯(lián)網(wǎng),如果有圖片或者內(nèi)容侵犯您的權(quán)益請聯(lián)系我們刪除!
3.本站所有原創(chuàng)作品,包括文字、資料、圖片、網(wǎng)頁格式,轉(zhuǎn)載時請標注作者與來源。
THE END