Show Limited Number of Tags after Posts

Recently I was  asked how to display a limited number of tags after each post in a customer’s WordPress theme I developed for them. Normally, you use a function the_tags() to display a link to the tags a post belongs to. If your post has 12 tags, and your theme only has space for 5, then it might not look 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, I will show you how you can limit the number of tags after posts in a WordPress theme without limiting the number of tags you add to each post.

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.

Leave a Comment