limit the number of tags after posts in your custom wordpress theme 1

In your WordPress theme, we were asked how to display a restricted number of tags after each post.

if you want to know how to show a limited number of tags follow this tutorial

number of tags

Normally, the tags() is used to display a link to the tags that a post belongs to. However, there is no argument to limit the number of tags displayed in that function. So, if your article contains 12 tags and your theme only allows for 5, the design may not be as appealing. Many people just limit the use of tags or don’t use them at all in their templates. However, in this article, we’ll show you how to limit the number of tags that appear after posts in your WordPress theme without limiting the amount of tags that you can add to individual posts.

Edit: It appears that after I published this blog, Otto (@otto42) responded on my Google+ account to inform me that there is a simpler way to accomplish this.

To begin, edit the functions.php file in your theme and add the following function:

1
2
3
4
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 modify the 5 to whichever number you like.

Then enter the following code into your loop.php, single.php, index.php, or anywhere you wish to add these post tags (must be inside a post loop):

1
<?php the_tags() ?>

This is a lot easier than what I came up with, which I’ll leave in this article for those who are interested.

An Antiquated and Complicated Method

Simply insert the following code (within the post loop) into your theme file:

1
2
3
4
5
6
7
8
9
10
11
12
13
<?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 the theme’s six tags where you will be able to see the limit of number of tags . Simply change the $count > 5 line to the desired value if you want to show fewer or more tags. Remember that, despite the fact that the count number is more than 5, we see six tags. Because the count begins at zero, this is the case. So, if you only want to show four tags, the number should be three.

You must edit line 9 if you want to change the separator. Commas will be used to divide the lines in the present code. You can also add divs, list components, and whatever else you want to tweak the styling.

Leave a Reply