Forums/Tips & Tricks

Show a list of items in a category, grouped by tag name

Michael Slater
posted this on February 19, 2012, 20:31

Suppose you have a category page, which gets the category passed in via the URL. (It must be a page of type "category"). It's simple enough to list out all the items of a certain type in that category:

<w:kb:item:each taxonomy="current" type="my_items">
    (code to display an item)
</w:kb:item:each>

But perhaps you want to group the items by tag, and show the tag subhead only if there are items of that category, with that tag. Here's the code:

<!-- capture the current category into a variable for later use -->
<w:var name='cat-name'><w:taxonomy:name /></w:var>
<h1>Category: <w:var name='cat-name' /></h1>
<!-- loop through the tags -->
<w:taxonomy:each name='tags'>
  <!-- display name of tag term and its items, if there are items of this type and with this tag -->
  <w:kb:item:if_items taxonomy='current&&categories:{{cat-name}}' type='my_items'>
    <h2><w:taxonomy:name /></h2> 
    <w:kb:item:each taxonomy='current&&categories:{{cat-name}}' type='my_items'>
      (code to display an item)
    </w:kb:item:each>
  </w:kb:item:if_items>
</w:taxonomy:each>

The key trick here is to capture the current category, passed from the URL and available as "current" until entering the taxonomy:each iterator, into a variable. Then you can access it inside that iterator.