首页 » Wordpress研究 » 2015-09-17 »
在 WordPress 的 Loop 循环中,我们习惯使用 the_tag() 来输出文章的所有标签,但是有时候因为样式排版的关系,我们可能只需要输出3、4个标签。Wordpress 官方函数 the_tag 以及相关的函数都无法直接做到这一点。这个时候就需要稍作“加工”。
方法一:
在 functions.php 中加入下列代码:
add_filter('term_links-post_tag','limit_to_five_tags'); function limit_to_five_tags($terms) { return array_slice($terms,0,5,true); } |
上述代码中的数字“5”,就是控制输出的条数。
然后在文章中直接使用
<?php the_tag() ?> |
就可以直接使其只输出5条标签。
方法二(相对古老的办法):
使用的是 get_the_tags() 函数,直接在你需要的地方输入下列标签输出代码即可
<?php $posttags = get_the_tags(); $count=0; $sep=''; if ($posttags) { echo 'Tags: '; foreach($posttags as $tag) { $count++; echo $sep . '<a href="'.get_tag_link($tag->term_id).'">'.$tag->name.'</a>'; $sep = ', '; if( $count > 5 ) break; //change the number to adjust the count } } ?> |
需要一提的是 $count > 5 是输出6条标签,修改数字“5”来控制输出的条数。
原文出处:How to Show Limited Number of Tags after Posts in your WordPress Theme