限制 WordPress 文章标签显示数

知更鸟 WordPress2322阅读模式

WordPress 默认标签函数the_tags没有数量限制,如果主题没有足够的显示位置,可能会造成页面混乱错位,我们可以通过下面的代码限制一下显示数量。

文章源自知更鸟-https://zmingcx.com/limit-the-number-of-wordpress-tabs-displayed.html

限制 WordPress 文章标签显示数

限制 WordPress 文章标签显示数

文章源自知更鸟-https://zmingcx.com/limit-the-number-of-wordpress-tabs-displayed.html

section

方法一文章源自知更鸟-https://zmingcx.com/limit-the-number-of-wordpress-tabs-displayed.html

将代码添加到当前主题函数模板 functions.php 中:文章源自知更鸟-https://zmingcx.com/limit-the-number-of-wordpress-tabs-displayed.html

add_filter( 'term_links-post_tag', 'zm_limit_tags' );
function zm_limit_tags( $terms ) {
	return array_slice( $terms, 0, 5, true );
}

修改其中的数字5,限制显示数量。文章源自知更鸟-https://zmingcx.com/limit-the-number-of-wordpress-tabs-displayed.html

section

方法二文章源自知更鸟-https://zmingcx.com/limit-the-number-of-wordpress-tabs-displayed.html

$posttags = get_the_tags();
$count = 0; $sep = '';
if ( $posttags ) {
	echo '标签: ';
	foreach( $posttags as $tag ) {
		$count++;
		echo $sep . '<a href="' . get_tag_link( $tag->term_id ) . '">' . $tag->name . '</a>';
		$sep = ', ';// 分隔符
		if( $count > 5 ) break; // 显示6个就写5
	}
}

用上述代码替换主题原来的:文章源自知更鸟-https://zmingcx.com/limit-the-number-of-wordpress-tabs-displayed.html

the_tags();

推荐用方法一,虽然不显示,但不影响标签归档,如果想自定义不同位置的标签数量就用方法二。文章源自知更鸟-https://zmingcx.com/limit-the-number-of-wordpress-tabs-displayed.html

 文章源自知更鸟-https://zmingcx.com/limit-the-number-of-wordpress-tabs-displayed.html 文章源自知更鸟-https://zmingcx.com/limit-the-number-of-wordpress-tabs-displayed.html

weinxin
我的微信
版权声明
本站原创文章转载请注明文章出处及链接,谢谢合作!
评论  2  访客  1  作者  1
    • 将来某天
      将来某天 0

      代码还是有点不懂呀

        • 知更鸟
          知更鸟

          @ 将来某天 代码只有几行,也确实比较简单,但不努力学习天天向上,俺也不懂,所以总结后,才分享记录一下

      匿名

      发表评论

      匿名网友 填写信息

      :?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

      确定