Filtering content with tags issue

The reason why this happens is because you define your $tags variable after the filtering takes place.

That means, if you articles collection is not filtered yet, you get all tags of all the articles, but if your collection is filtered, then you only get the tags of the filtered collection.

To avoid this from happening, move your $tags definition up in your code

 // fetch the basic set of pages
  $articles = $page->children()->visible()->flip();

  // fetch all tags
  $tags = $articles->pluck('tags', ',', true);

  // add the tag filter
  if($tag = param('tag')) {
    $articles = $articles->filterBy('tags', $tag, ',');
  }

The active class must be added where you output the tags.

$activeTag = param('tag');

foreach($tags as $tag):
  if($tag == $activeTag):
     // add class active
  endif;
endforeach;