咱們在編寫文章時,常常須要添加一些標籤關鍵詞的連接,這樣不只能夠優化咱們的內鏈,對用戶來講也能夠參照相關的文章,若是對文章的關鍵字進行手動添加連接,那樣對咱們來講太麻煩了,並且在標籤關鍵詞不少的狀況下咱們是記不住的,今天就向你們介紹如何讓咱們的wordpress文章自動添加標籤關鍵詞的連接:php
打開咱們主題的functions.php文件添加以下代碼:wordpress
//鏈接數量 $match_num_from = 1; //一個關鍵字少於多少不替換 $match_num_to = 10; //一個關鍵字最多替換 //鏈接到WordPress的模塊 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; }