How to Show Limited Number of Tags after Posts in your WordPress Theme

136

Recently we were asked how to display a limited number of tags after each post in your WordPress theme. Normally, you use a function the_tags() to display a link to the tags a post belongs to. However that function does not have a parameter to limit the number of tags displayed. So if your post has 12 tags, and your theme only has space for 5, then it might not look so good in the design. A lot of folks just limit the usage of tags, or don’t even include it in the templates. But in this article, we will show you how you can limit the number of tags after posts in your WordPress theme without limiting the number of tags you add to each post.

Edit: Apparently after writing this article, the most awesome Otto (@otto42) replied on my Google+ account to let me know that there is a simpler way of accomplishing this.

First you need to open your theme’s functions.php file and add this function:

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

You can change the 5 number to maximum count you want.

Then open your loop.php, single.php, index.php, or wherever you want to add these post tags (must be inside a post loop), then paste the following code:

<?php the_tags() ?>

This is definitely a lot simpler than what I had come up with which I will leave in this post for those who care.

Old Complicated Method

All you need to do is paste the following code in your theme file (inside the post loop):

  <?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  	}  }  ?>  

The code above will display 6 tags in the theme. If you want to show less tags or more tags, simply adjust the $count > 5 line with the number you want. Remember, even though the count number says greater than 5, we see 6 tags. That is because the count is starting at 0. So if you want to show only 4 tags, then the number would need to be 3.

If you want to change the separator, then you need to change line 9. The current code will separate by commas. You can also customize the styling by adding divs, list elements, or anything else that you like.