Part of the code is responsible for calling tags in the list of articles. How to set a maximum of 5 tags for example. thank

<?php $tags = K2ModelItem::getItemTags($item->id); for ($i=0; $i<sizeof($tags); $i++) { $tags[$i]->link = JRoute::_(K2HelperRoute::getTagRoute($tags[$i]->name)); } $item->tags=$tags; ?> <?php if(count($item->tags)): ?> <!-- Item tags --> <?php foreach ($item->tags as $tag): ?> <li><a href="<?php echo $tag->link; ?>"><?php echo $tag->name; ?></a></li> <?php endforeach; ?> 
  • what a nightmare - John Doe

1 answer 1

In a for-cycle, you should correct the condition for completing the cycle by adding the condition $i < 5

 for ($i=0; $i < sizeof($tags) && $i < 5; $i++) { ... } 

Or modify the K2ModelItem::getItemTags() method so that it would accept an optional optional parameter restricting the selection.

 function getItemTags($id, $limit = null) { ... } 

Then it will be possible to limit any number of elements.

 $tags = K2ModelItem::getItemTags($item->id, 5); 

Then in the foreach loop, add the output for the same condition.

  <?php $counter = 0; ?> <?php foreach ($item->tags as $tag): ?> <?php if (++$counter > 5) break; ?> <li><a href="<?php echo $tag->link; ?>"><?php echo $tag->name; ?></a></li> <?php endforeach; ?> 
  • I tried both methods. None of them worked. - Ivan
  • @Ivan added an answer - cheops