Flexibility in displaying tags

I’m playing around with tags and looking to achieve either of these two options:

  1. On the homepage, display the first 3 tags associated with an article page and then truncate the 4th eg. “Blue, Green, Red, Ora…”

  2. On the homepage, display the first 3 tags then show how many more tags are associated numerically eg. “Blue, Green, Red (8 more)”

Heres my code - any ideas on how best to achieve?

                <?php if($article->tags()->isNotEmpty()): ?>

                <div class="entry-tags">
     
                    <?php foreach(str::split($article->tags()) as $tag): ?>
                        <a href="<?= url($site->url() . '/' . url::paramsToString(['tag' => $tag])) ?>" rel="category tag"><?= $tag; ?></a>
                    <?php endforeach ?>
                </div>

            <?php endif ?>
<?php 
  $tags = $article->tags()->split();
  $count = count($tags);
  dump($count);
  $threeTags = array_slice($tags, 0, 3);
?>

This gives you three of the tags and the counter.

For the other option, you’d have to get the fourth element, if available, and use string functions to cut of the first x letters.

As an alternative, you can also create a collection from your tags:

<?php 

$tags = (new Collection($page->tags()->split()))->limit(4);

foreach($tags as $tag) {
  if($tags->indexOf($tag) == 3) {
    echo substr($tag,0,3).'…';
  } else {
    echo $tag;
  }
 
}

?>
1 Like

This is exactly what I was after, thank you! Although the first snippet doesn’t seem to only display the first 3 tags, instead it shows all of them. Any ideas why this might be?

                <?php if($article->tags()->isNotEmpty()): ?>

                <div class="entry-tags">
     
                    <?php foreach(str::split($article->tags()) as $tag): ?>
                        <a href="<?= url($site->url() . '/' . url::paramsToString(['tag' => $tag])) ?>" rel="category tag"><?= $tag; ?></a>
                    <?php endforeach ?>
                    
                    <?php 
                      $tags = $article->tags()->split();
                      $count = count($tags);
                      dump($count);
                      $threeTags = array_slice($tags, 0, 3);
                    ?>

                </div>  

            <?php endif ?>

Well, you are looping through all tags, and then you put the code I suggested after your foreach loop, which doesn’t make sense. The code was intended to replace your loop…i.e. you’d then loop through $threeTags. Same with the second suggestion.

1 Like