wordpress如何實現tag標籤內鏈?網上有人說使用外掛。
一開始我也是在網上看到別人推薦,使用的Simple Tags這個外掛來完成tag內鏈的。
但是使用後,效果並不明顯,很多打了標籤卻不內鏈。也不知道是不是我沒有設定對。
最近又在網上找了一個方法,不利用外掛來實現TAG內鏈,當然也是聽到網友說使用外掛會使網站速度變慢,索性直接換成了程式碼方式實現。
將程式碼放在當前主題Functions.php 檔案中。
也可透過後臺 外觀-主題編輯器 進入編輯。
將程式碼放在結尾 ?> 的前面
//自動TAG轉內鏈
$match_num_from = 2; // 一個TAG標籤出現幾次才加連結
$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;
}