当前位置:K88软件开发文章中心编程全书编程全书02 → 文章内容

WordPress 自动为文章标签(关键词)添加该标签的链接

减小字体 增大字体 作者:佚名  来源:网上搜集  发布时间:2019-1-4 9:20:47

-->

有一天我在给某篇文章评论的时候,偶尔看到了“斌果”朋友问的:有没有自动将文章中出现的标签放上链接?然后多次探索探究找到了自动将文章中出现的标签加链接的方法。这方法很简单,将下面的代码添加到主题的 functions.php 即可:

1234567891011121314151617181920212223242526272829303132333435363738
/** * WordPress 自动为文章标签添加该标签的链接 * http://www.wpdaxue.com/auto-add-tag-link.html */$match_num_from = 1;  // 一个标签在文章中出现少于多少次不添加链接$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;}

你可以根据自己的需要修改文章标签的链接数。

PS:真的找不到该代码的原始出处,如果有知道的,烦请告知。

测试:该代码会自动为这篇文章的标签添加链接,但是 $match_num_from 和 $match_num_to 这两个参数的设置很有意思(不够准确,具体请自己测试)


WordPress 自动为文章标签(关键词)添加该标签的链接