WordPress 文章如何自动增加关键词为内链【非插件】
摘要: 折腾一个路由器网站(hruanjian.com),也遇到了一个问题WordPress 文章如何自动增加关键词为内链,在网站上实践后发现可行没有任何问题,特此记录。方法就是将下面的代码放到跟目录下面的functions.php,就OK了。// ...
折腾一个路由器网站(hruanjian.com),也遇到了一个问题WordPress 文章如何自动增加关键词为内链,在网站上实践后发现可行没有任何问题,特此记录。
方法就是将下面的代码放到跟目录下面的functions.php,就OK了。
//WordPress 文章关键词自动内链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){$match_num_from = 1; //一个标签少于几次不链接$match_num_to = 1; //一个标签最多链接几次$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," '$'),__('更多关于="" %s="" 的文章'))."\"";="" $url="" .=" target="_blank"" ;="" .addcslashes($cleankeyword,="" '$')."<="" a="">";$limit = rand($match_num_from,$match_num_to);//不链接代码$content = preg_replace( '|(<a[^>]+>)(.*)<pre.*?>('.$ex_word.')(.*)<\/pre>(</pre.*?></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.*?)))('.></img)(.*?)('.$ex_word.')(.*?)(></a>))\'s' . $case;$content = preg_replace($regEx,$url,$content,$limit);$content = str_replace( '%&&&&&%', stripslashes($ex_word), $content);}}return $content;}add_filter('the_content','tag_link',1);