我們在編寫文章時,經常需要添加一些標簽關鍵詞的鏈接,這樣不僅可以優化我們的內鏈,對用戶來說也可以參照相關的文章,如果對文章的關鍵字進行手動添加鏈接,那樣對我們來說太麻煩了,而且在標簽關鍵詞很多的情況下我們是記不住的,那怎么如何讓WordPress站點的文章自動添加標簽鏈接變為內鏈呢?其實我們只需要在主題目錄下的functions.php文件中添加一段代碼就可以實現了。
只需要在模板函數文件【functions.php】添加下面代碼:
//自動關鍵詞內鏈 $match_num_from?=?1;?//一個關鍵字少于多少不替換 $match_num_to?=?5;?//一個關鍵字最多替換 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>”.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(?‘|(@@##@@)|U’.$case,?‘$1$2%&&&&&%$4$5′,?$content); $cleankeyword?=?preg_quote($cleankeyword,’”); $regEx?=?‘’(?!((<.>]*?)>)|([^>]*?))’s’?.?$case; $content?=?preg_replace($regEx,$url,$content,$limit); $content?=?str_replace(?‘%&&&&&%’,?stripslashes($ex_word),?$content); } } return?$content; }</.>
上面代碼添加到模板函數最后面 ” ?>” 前方,一定要保持格式和符號不要更改,然后更新模板函數,清除瀏覽器緩存后重新打開一個文章頁面就會看的到效果了。
更多wordpress相關技術文章,請訪問wordpress教程欄目進行學習!
? 版權聲明
文章版權歸作者所有,未經允許請勿轉載。
THE END